objective-c

[objective-c]GCDを使った非同期処理

GCDを使った非同期処理
GCD:Grand Central Dispatch

dispatch_queue_t main=dispatch_get_main_queue();
dispatch_queue_t sub=dispatch_queue_create("net.ktyr.sample", NULL);
dispatch_async(sub, ^{
    //何か重たい処理
    UIImage*image=[UIImage imageNamed:@"thankyou.png"];
    dispatch_async(main, ^{
        //重たい処理が終わったとき
        [myImageView setImage:image];
    });
});
dispatch_release(sub);

[objective-c]RGBAで指定した色のUIImageを生成

RGBAで指定した色のUIImageを生成

-(UIImage*)get255ColorRectImage:(float)r g:(float)g b:(float)b alpha:(float)alpha size:(CGSize)_size{
    UIGraphicsBeginImageContext(_size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, r/255.0,g/255.0,b/255.0,alpha/255.0);
    CGContextFillRect(context, CGRectMake(0.0,0.0,_size.width,_size.height));
    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenImage;
}

UIImage*redImage=[self get255ColorRectImage:255.0 g:0.0 b:0.0 alpha:255.0 size:CGSizeMake(100, 100)];

[objective-c]UITabBarの背景を削除する

UITabBarの背景を削除する

-(void)removeTabBarBackground:(UITabBar*)_tab{
    for(UIView*t in _tab.subviews){
        NSString*s=NSStringFromClass([t class]);
        if ([s isEqualToString:@"UITabBarButton"] || t==_tab) {
            continue;
        }
        [t removeFromSuperview];
        break;
    }
}

[self removeTabBarBackground:_mytab];

[objective-c]UITouchからCGPoint取得

UITouchからCGPoint取得

-(CGPoint)getCGPointByUITouch:(UITouch*)t{
    return [t locationInView:self.view.superview];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSArray*t=[touches allObjects];
    CGPoint tp1=[self getCGPointByUITouch:[t objectAtIndex:0]];
}

[objective-c]NSDateからNSString生成

NSDateからNSString生成

-(NSString*)getStringByDate:(NSDate*)_date{
    NSDateFormatter*df=[[NSDateFormatter alloc] init];
    NSCalendar*cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [df setCalendar:cal];
    [df setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSString* str=[df stringFromDate:_date];
    [cal release];
    [df release];
    return str;
}

[objective-c]GameCenter

なんとなく作ったGameCenterManager

#import "GameCenterManager.h"

GameCenterManager*gcm;
gcm=[[GameCenterManager alloc]initWithDelegate:self func:@selector(whenGameCenterEvent:)];
[gcm authenticateLocalPlayer];

-(void)whenGameCenterEvent:(NSNumber*)nm{
    NSLog(@"whenGameCenterEvent %d",[nm intValue]);
}

GameCenterManager.h

#import 
#import 

@interface GameCenterManager : NSObject{
    BOOL login;
@private
    
    id del;
    SEL func;
    /*
     1:認証成功
     2:認証失敗
     3:スコア報告成功
     4:スコア報告失敗
     5:リーダーボード表示失敗
    */
}
@property(nonatomic,assign)BOOL login;
-(id)initWithDelegate:(id)_d func:(SEL)_f;
- (void) authenticateLocalPlayer;
- (void) reportScore: (int64_t) score forCategory: (NSString*) category;
-(void)reportScore:(int64_t)score;
- (void) showLeaderboard;

@end

GameCenterManager.m


#import "GameCenterManager.h"

@implementation GameCenterManager

static NSString*leaderBoardID=@"hoge";

@synthesize login;

-(id)init{
    self=[super init];
    if (self) {
        login=NO;
    }
    return self;
}
-(id)initWithDelegate:(id)_d func:(SEL)_f{
    self=[self init];
    del=_d;
    func=_f;
    return self;
}
-(void)exeEvent:(int)t{
    NSNumber*n=[NSNumber numberWithInt:t];
    if (del && func && [del respondsToSelector:func]) {
        [del performSelector:func withObject:n];
    }
}



-(void)dealloc{
    del=nil;
    func=nil;
    [super dealloc];
}


//step1:プレーヤー認証 最速で実行
- (void) authenticateLocalPlayer
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    [localPlayer authenticateWithCompletionHandler:^(NSError *error) {
        if (localPlayer.isAuthenticated){
            // 認証済みプレーヤーの追加タスクを実行する
            login=YES;
            [self exeEvent:1];
        }else{
            [self exeEvent:2];
        }
        }];
}


//step2:スコア報告
//category:リーダーボードのID
- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
    if (!login) {
        [self exeEvent:4];
        return;
    }
    GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category]autorelease];
    scoreReporter.value = score;
    [scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
        if (error != nil){
            // 報告エラーの処理
            [self exeEvent:4];
        }else{
            [self exeEvent:3];
        }
        }];
}
-(void)reportScore:(int64_t)score{
    [self reportScore:score forCategory:leaderBoardID];
}

- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController*)viewController
{
    [viewController dismissModalViewControllerAnimated:YES];
}

//リーダーボード表示
- (void) showLeaderboard
{
    GKLeaderboardViewController *leaderboardController =[[[GKLeaderboardViewController alloc] init]autorelease];
    if (leaderboardController != nil)
    {
        leaderboardController.leaderboardDelegate=self;
        [del presentModalViewController: leaderboardController animated: YES];
    }else{
        [self exeEvent:5];
    }
}

@end

[objective-c]音

//ヘッダーファイル
#import <AudioToolbox/AudioToolbox.h>

SystemSoundID soundID0;
//初期化
NSString *path;
NSURL *url;
    
path= [[NSBundle mainBundle] pathForResource:@"move" ofType:@"mp3"];
url= [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID0);

//再生
AudioServicesPlaySystemSound(soundID0);

[objective-c]UIViewが格納されたNSArrayをorigin.xでソート

UIViewが格納されたNSArrayをorigin.xでソート

-(NSArray*)sortByOriginX:(NSArray*)list{
    NSMutableArray*t=[NSMutableArray arrayWithArray:list];
    [t sortUsingComparator:^(id _v1,id _v2){
        UIView*v1=(UIView*)_v1;
        UIView*v2=(UIView*)_v2;
        return (v1.frame.origin.x==v2.frame.origin.x)?NSOrderedSame:((v1.frame.origin.x<v2.frame.origin.x)?NSOrderedAscending:NSOrderedDescending);
    }];
    return t;
}