分类 Object-C 下的文章

object-c调用网址缩短api

短网址文档地址: usr.im

NSString *requestUrl = [NSString stringWithFormat:
                                 @"http://api.usr.im/short.txt?url=%@", @"http://tool.lu/"];
NSString *shortUrl = [NSString stringWithContentsOfURL:[NSURL URLWithString:requestUrl]
                                                   encoding:NSUTF8StringEncoding error:nil];
// NSLog(@"%@", url);

[SysStatus app] 模拟monitorplus状态栏

首先看效果:

screenshot2-1.png
2014-02-24 14\_03\_06.gif

下面是所用到的颜色:

screenshot1.png

分析:

detail.png

代码

因为是demo,所以很多地方的代码组织不完善。

//
//  StatusItemView.h
//  SysStatus
//
//  Created by xiaozi on 14-2-23.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "ProgressView.h"

@interface StatusItemView : NSControl <NSMenuDelegate> {
    NSStatusItem *_statusItem;
    BOOL _isHighlighted;
    NSDictionary *_data;
    SEL _action;
    id __unsafe_unretained _target;
    ProgressView *_cpuView;
    ProgressView *_memView;
}

@property (nonatomic, readonly) NSStatusItem *statusItem;
@property (nonatomic, setter = setHighlighted:) BOOL isHighlighted;
@property (nonatomic) NSDictionary *data;
@property (nonatomic) SEL action;
@property (nonatomic, unsafe_unretained) id target;

- (id) initWithStatusItem: (NSStatusItem *)statusItem;

@end
//
//  StatusItemView.m
//  SysStatus
//
//  Created by xiaozi on 14-2-23.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import "StatusItemView.h"
#import "ProgressView.h"

@implementation StatusItemView

- (id) initWithStatusItem: (NSStatusItem *)statusItem
{
    self = [super init];
    if (self) {
        // Initialization code here.
        _statusItem = statusItem;
        _cpuView = [[ProgressView alloc] initWithFrame: NSMakeRect(0, 10, 82, 11)];
        [_cpuView setBarColor:[NSColor colorWithCalibratedRed:0.91 green:0.3 blue:0.24 alpha:1]];
        [_cpuView setData:[NSDictionary dictionaryWithObjectsAndKeys:@"CPU %3d%%", @"label", [NSNumber numberWithInt: 0], @"value", nil]];
        _memView = [[ProgressView alloc] initWithFrame: NSMakeRect(0, 1, 82, 11)];
        [_memView setBarColor:[NSColor colorWithCalibratedRed:0.29 green:0.64 blue:0.87 alpha:1]];
        [_memView setData:[NSDictionary dictionaryWithObjectsAndKeys:@"MEM %3d%%", @"label", [NSNumber numberWithInt: 0], @"value", nil]];
        [self addSubview:_cpuView];
        [self addSubview:_memView];
    }
    return self;
}

- (void) setData: (NSDictionary *)data
{
    [_cpuView setData:[NSDictionary dictionaryWithObjectsAndKeys:@"CPU %3d%%", @"label", [data objectForKey: @"cpu"], @"value", nil]];
    [_memView setData:[NSDictionary dictionaryWithObjectsAndKeys:@"MEM %3d%%", @"label", [data objectForKey: @"mem"], @"value", nil]];
}

- (void) setHighlighted: (BOOL) highlighted
{
    if (_isHighlighted == highlighted) return;
    _isHighlighted = highlighted;
    [_cpuView setHighlighted: highlighted];
    [_memView setHighlighted: highlighted];
    [self setNeedsDisplay: YES];
}

- (void) setMenu:(NSMenu *)menu
{
    [menu setDelegate: self];
    [super setMenu: menu];
}

- (void)mouseDown:(NSEvent *)theEvent
{
    [_statusItem popUpStatusItemMenu: [super menu]];
    [NSApp sendAction:_action to:_target from:self];
}

- (void)menuWillOpen:(NSMenu *)menu {
    [self setHighlighted:YES];
    [self setNeedsDisplay:YES];
}

- (void)menuDidClose:(NSMenu *)menu {
    [self setHighlighted:NO];
    [self setNeedsDisplay:YES];
}

- (void)drawRect:(NSRect)dirtyRect
{
    [_statusItem drawStatusBarBackgroundInRect:dirtyRect withHighlight: _isHighlighted];

}

@end
//
//  ProgressView.m
//  SysStatus
//
//  Created by xiaozi on 14-2-24.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import "ProgressView.h"

@implementation ProgressView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        _data = [NSDictionary dictionaryWithObjectsAndKeys:@"LAB %3d%%", @"label", [NSNumber numberWithInt: 50], @"value", nil];
        _barColor = [NSColor colorWithCalibratedRed:0.91 green:0.3 blue:0.24 alpha:1];
    }
    return self;
}

- (void) setHighlighted:(BOOL)highlighted
{
    if (_highlighted == highlighted) return;
    _highlighted = highlighted;
    [self setNeedsDisplay: YES];
}

-(void) setData:(NSDictionary *)data
{
    _data = data;
    [self setNeedsDisplay: YES];
}

- (void)drawRect:(NSRect)dirtyRect
{
    NSColor *fontColor,*barBorderColor,*barIndicatorColor,*barBgColor;
    if (_highlighted) {
        fontColor = [NSColor whiteColor];
        barBorderColor = [NSColor whiteColor];
        barIndicatorColor = [NSColor whiteColor];
        barBgColor = [NSColor clearColor];
    } else {
        fontColor = [NSColor blackColor];
        barBorderColor = [NSColor colorWithCalibratedRed:0.17 green:0.24 blue:0.3 alpha:1];
        barIndicatorColor = _barColor;
        barBgColor = [NSColor colorWithCalibratedRed:0.95 green:0.96 blue:0.96 alpha:1];
    }
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Menlo" size: 8], NSFontAttributeName, fontColor, NSForegroundColorAttributeName, nil];
    NSAttributedString * text=[[NSAttributedString alloc] initWithString:[NSString stringWithFormat: [_data valueForKey:@"label"], [[_data objectForKey: @"value"] integerValue]] attributes: attributes];
    [text drawAtPoint:NSMakePoint(6, 1)];
    
    NSRect bar = NSMakeRect(50.0f, 3, 27.0f, 6.0f);
    bar = NSInsetRect(bar, .5f, .5f);
    NSBezierPath *barView = [NSBezierPath bezierPathWithRect: bar];
    [barBgColor set];
    [barView fill];
    [barBorderColor set];
    [barView stroke];
    NSRect barIndicator = NSMakeRect(50.0f, 3, roundf(.27f * [[_data objectForKey: @"value"] integerValue]), 6.0f);
    barIndicator = NSInsetRect(barIndicator, 1, 1);
    [barIndicatorColor set];
    [NSBezierPath fillRect:barIndicator];
}

@end

使用方法

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    NSStatusItem *statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:82];
    statusItemView = [[StatusItemView alloc] initWithStatusItem: statusItem];
    [statusItem setHighlightMode: YES];
    [statusItem setView: statusItemView];
    [statusItemView setMenu: _statusMenu];
    
    [NSTimer scheduledTimerWithTimeInterval:2
                                      target:self
                                    selector:@selector(updateInfo:)
                                    userInfo:nil
                                     repeats:YES];
}

- (void)updateInfo:(NSTimer *)timer
{
    int cpuUsage = (arc4random() % 20) + 2;
    int memUsage = (arc4random() % 10) + 50;
//    NSLog(@"%d, %d", cpuUsage, memUsage);
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt: cpuUsage], @"cpu", [NSNumber numberWithInt: memUsage], @"mem", nil];
    [statusItemView setData: data];
}

[awake app] 自定义StatusItemView

2014-02-23 16\_43\_29.gif

源码已经放在github

左击切换状态,右击显示菜单;但是NSStatusItem没有提供右键菜单,所以要定义自己的View;若果需要直接方便使用的话,有开源框架RHStatusItemView,引入项目中就可以用了。下面是我自己实现的:

//
//  StatusItemView.h
//  awake
//
//  Created by xiaozi on 14-2-21.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface StatusItemView : NSControl <NSMenuDelegate>{
    NSImage *_image;
    NSImage *_alternateImage;
    NSStatusItem *_statusItem;
    BOOL _isHighlighted;
    SEL _action;
    SEL _rightAction;
    id __unsafe_unretained _target;
}

@property (nonatomic, readonly) NSStatusItem *statusItem;
@property (nonatomic, strong) NSImage *image;
@property (nonatomic, strong) NSImage *alternateImage;
@property (nonatomic, setter = setHighlighted:) BOOL isHighlighted;
@property (nonatomic) SEL action;
@property (nonatomic) SEL rightAction;
@property (nonatomic, unsafe_unretained) id target;

- (id) initWithStatusItem: (NSStatusItem *) statusItem;

@end
//
//  StatusItemView.m
//  awake
//
//  Created by xiaozi on 14-2-21.
//  Copyright (c) 2014年 xiaozi. All rights reserved.
//

#import "StatusItemView.h"

@implementation StatusItemView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void) drawRect:(NSRect)dirtyRect
{
    [_statusItem drawStatusBarBackgroundInRect:dirtyRect withHighlight:_isHighlighted];
    NSImage *icon = _isHighlighted ? _alternateImage : _image;
    NSSize iconSize = [icon size];
    NSRect bounds = [self bounds];
    
    CGFloat iconX = roundf((NSWidth(bounds) - iconSize.width) / 2);
    CGFloat iconY = roundf((NSHeight(bounds) - iconSize.height) / 2);
    NSPoint iconPoint = NSMakePoint(iconX, iconY);
    [icon drawAtPoint:iconPoint fromRect:bounds operation:NSCompositeSourceOver fraction:1.0];
}

- (id) initWithStatusItem: (NSStatusItem *) statusItem {
    CGFloat itemWidth = [statusItem length];
    CGFloat itemHeight = [[NSStatusBar systemStatusBar] thickness];
    NSRect itemRect = NSMakeRect(0.0, 0.0, itemWidth, itemHeight);
    self = [self initWithFrame:itemRect];
    if (self != nil)
    {
        _statusItem = statusItem;
        [_statusItem setView: self];
    }
    return self;
}

- (void)setMenu:(NSMenu *) menu {
    [menu setDelegate: self];
    [super setMenu: menu];
}

- (void)setHighlighted:(BOOL)newFlag
{
    if (_isHighlighted == newFlag) return;
    _isHighlighted = newFlag;
    [self setNeedsDisplay:YES];
}

- (void)mouseDown:(NSEvent *)theEvent
{
    [NSApp sendAction:_action to:_target from:self];
}

- (void)rightMouseDown:(NSEvent *)theEvent
{
    NSMenu *menu = [super menu];
    [_statusItem popUpStatusItemMenu:menu];
    [NSApp sendAction:_rightAction to:_target from:self];
}

- (void)menuWillOpen:(NSMenu *)menu {
    [self setHighlighted:YES];
    [self setNeedsDisplay:YES];
}

- (void)menuDidClose:(NSMenu *)menu {
    [self setHighlighted:NO];
    [self setNeedsDisplay:YES];
}

- (void)setImage:(NSImage *)newImage
{
    _image = newImage;
    [self setNeedsDisplay: YES];
}

- (void)setAlternateImage:(NSImage *)newImage
{
    _alternateImage = newImage;
    if (_isHighlighted)
        [self setNeedsDisplay:YES];
}

- (BOOL)isOpaque
{
    return YES;
}

@end

具体使用方法:

statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: 22.0];
[statusItem setHighlightMode:YES];
statusView = [[StatusItemView alloc] initWithStatusItem: statusItem];
[statusView setMenu: statusMenu];
// [statusItem setView: statusView];
[statusView setImage: [NSImage imageNamed:@"MenuIcon"]];
[statusView setAlternateImage: [NSImage imageNamed:@"MenuIconSelected"]];

[statusView setAction: @selector(clickStatusItem:)];

object-c in_array

判断的三种方式:

//
//  main.m
//  learning
//
//  Created by xiaozi on 13-12-8.
//  Copyright (c) 2013年 xiaozi. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSString* extsStr = @"php,js,py";
        NSArray* extsArr = [extsStr componentsSeparatedByString:@","];
        
        // 是否在数组中 {{{
        NSPredicate* rule1 = [NSPredicate predicateWithFormat:@"SELF IN %@", extsArr];
        BOOL result1 = [rule1 evaluateWithObject:@"txt"];
        NSLog(@"%d", result1);
        // }}}
        
        // {{{
        NSPredicate* rule2 = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", @"js"];
        
        // 数组包含
        BOOL result2 = [rule2 evaluateWithObject:extsArr];
        NSLog(@"%d", result2);
        // }}}
        
        // 数组过滤
        BOOL result3 = [[extsArr filteredArrayUsingPredicate:rule2] count];
        NSLog(@"%d", result3);
        
    }
    return 0;
}

cocoa项目中嵌入python

添加链接库:
A5C731A1-10A4-46B3-AF78-A32AB4AF9CA2.png

文件结构:
QQ20130107-1.png

代码

main.m

#import 
#import 

int main(int argc, char *argv[]) {
    Py_Initialize();
    // 这里面自己定义一个hello函数(python的)好了
    PyRun_SimpleString("import hmac, binascii\n"
                       "from itertools import izip, cycle\n");
    int result = NSApplicationMain(argc, (const char **)argv);
    Py_Finalize();
    return result;
}

控制器里面直接使用就好了

- (IBAction)runpy:(id)sender {
    PyObject *m, *f, *a, *k;

    m = PyImport_ImportModule("__main__");
    f = PyObject_GetAttrString(m, "hello");
    a = PyTuple_Pack(1, PyString_FromString([[_email stringValue] UTF8String]));
    k = PyObject_CallObject(f, a);
    
    // NSLog(@"%@", [NSString stringWithUTF8String:PyString_AsString(k)]);
    [_keycode setStringValue:[NSString stringWithUTF8String:PyString_AsString(k)]];
    
    Py_DECREF(k);
    Py_DECREF(a);
    Py_DECREF(f);
    Py_DECREF(m);
}

JSONKit杂记

记录

写程序时遇到的几个问题,记录一下。

  • 加到project里面的时候不能加在子目录下
  • 编译的时候需要指定JSONKit.m的compiler flags "-fno-objc-arc"

吐槽

object-c的函数长度真心是伤不起的,截图留念!

sublime text2 svn sftp plugin keygen

第一次写object-c程序,写了好几个小时才写出来这么个小东西。

  1. 反编译pyc文件,查看算法
  2. 写出key生成的算法
  3. 将python嵌入Object-C,得到最终的程序

将email和生成的key写入插件目录下的sublime-setting文件。

"email": "your email",
"product_key": "the key",

下载地址:svn-sftp-keygen.app.zip

2013-03-19 增加 邮件获取注册码

发送任何邮件到 bot[at]tool.lu, 系统会自动生成注册码,并回复到你的发件邮箱

2013-04-24 增加 osx10.7支持,优化算法机

QQ20130424-1.png
下载地址:svn-keygen.app.zip