Category: ‘Objective-C’

Xcodeの必須ショートカット

2014年5月6日 Posted by PURGE

■.hファイルと.mファイルの切り替え
Command + Ctrl + ↑

■ビルド
Command + R

UIView の背景色/背景画像を設定する

2014年5月3日 Posted by PURGE

■UIViewに背景色を設定

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.3f
                                                green:0.5f
                                                 blue:0.8f
                                                alpha:1.0f];
}

■UIViewに背景画像を設定

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *backGroundImage = [UIImage imageNamed:@"backgroundImg"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backGroundImage];
}

ちなみに、backgroundImg の画像名は、Images.xcassets で読み込んだ画像です。

NSRangeException

2014年2月15日 Posted by PURGE

どうやら配列絡みのエラーっぽい。

Terminating app due to uncaught exception 'NSRangeException', 
reason: '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'

下記のメソッドで返されたカウントより範囲を超えてしまっているようだ。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return items.count;
}

よくよく見ると、storybordでのtableViewのcontent設定が、Static Cells に設定されていたことに気づく。
ここは、Dynamic Prototypes 設定でしょ。

NSInternalInconsistencyException

2014年2月15日 Posted by PURGE

最近はプライベートで全くプログラムをやる気も無くなっていて久しぶりに iOSプログラミング。
そこで早速ハマったエラー。

テーブルビューが表示されないので、下記の戻り値を1に設定する。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

しかし、NSInternalInconsistencyExceptionエラーとなる。
どうやら、storyboardで画面遷移をしないので、何か矛盾が起きているようだ。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'unable to dequeue a cell with identifier Cell - 
must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

以下のコメントアウト部分でエラーとなっていた。
indexPathに見合うidentifierが見つからないようだ。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = @"セル";
    return cell;
}

結局、コメントアウト部分をコメントアウトして、cellのnil判定で初期化する処理を記述。
うまく行ったようです。

やっぱり、テンプレートで作成されたソースコードを良くみないと、自分で記述する場合と、storyboardを使用する場合の記述方法には、今後も気をつけないと。

UIButtonのタイトル変更

2013年11月25日 Posted by PURGE

UIButtonのタイトルが変わらないので、下記のようにsetTitle:forstateで変更するようだ。

[Btn setTitle:@"変更" forState:UIControlStateNormal];

isEqualToDate と NSDateFommatter

2013年11月21日 Posted by PURGE

NSDate型に、時間が同じかどうかを判定するメソッドがある。
(BOOL)isEqualToDate:(NSDate *)anotherDate
しかし、当然のことながら、1秒でも数値が異なると、日付判定が異なってしまう。なので、NSString型で比較。

    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    [fmt setDateFormat:@"yyyy/MM/dd"];
    NSString *currentDate = [fmt stringFromDate:[NSDate date]];
    NSString *tommorowDate = [fmt stringFromDate:[NSDate dateWithTimeIntervalSinceNow:60*60*8]];
    
    NSLog(@"現在:%@", currentDate);
    NSLog(@"明日:%@", tommorowDate);
    
    if ([currentDate isEqualToString: tommorowDate]) {
        NSLog(@"同日です。");
    }else{
        NSLog(@"同日ではありません。");
    }

ちなみに、NSString型同士で、== で比較すると falseとなります。

    if (currentDate == tommorowDate) {
        NSLog(@"同日です。%@", result);
    }else{
        NSLog(@"同日ではありません。%@", result);
    }

Objective-C のクラス定義

2013年8月24日 Posted by PURGE

久しぶりに、Objective-C の勉強。はっきり言って基本すら忘れてます。

sample.h

@interface クラス名 : 親クラス
{

}
@property プロパティ型 プロパティ名 
@end

sample.m

@implmentation クラス名
@synthesize プロパティ名;
  //メソッド実装
@end

CocoaPods インストール

2013年8月23日 Posted by PURGE

急遽、CocoaPodsというものを使うこととなった。
その覚え書き。

$ gem install cocoapods

gem にてインストールらしいが、podコマンドを打っても認識できていない。
一応環境は、Mac + rbenv で構築されている。

$ rbenv rehash
$ pod setup
Setting up CocoaPods master repo
Setup completed (read-only access)

セットアップされたようだ。

$ pod --version
0.23.0

その後、PodFileを作成して実行
PodFile

platform :ios, '6.0'
pod 'DCIntrospect'
pod 'GHUnitIOS'
pod 'BlocksKit'
pod 'Underscore.m'
pod 'AQGridView'
pod 'QuickDialog'
pod 'JASidePanels'
pod 'OCCalendar'
pod 'SDWebImage'
pod 'SVProgressHUD'
pod 'Reachability'
pod 'AFNetworking', '1.3.2'
pod 'MagicalRecord'
pod 'NoticeView'
pod 'ELCImagePickerController'
$ pod install
Analyzing dependencies
Downloading dependencies
Installing AFNetworking (1.3.2)
Installing AQGridView (1.3)
Installing BlocksKit (1.8.2)
Using DCIntrospect (0.0.2)
Installing ELCImagePickerController (0.1.2)
Installing GHUnitIOS (0.5.6)
Installing JASidePanels (1.3.2)
Installing MagicalRecord (2.1)
Installing NoticeView (3.0.7)
Installing OCCalendar (0.0.3)
Installing QuickDialog (0.8)
Installing Reachability (3.1.1)
Installing SDWebImage (3.4)
Installing SVProgressHUD (0.9)
Installing Underscore.m (0.2.1)
Installing libffi (3.0.13)
Installing libwebp (0.3.0-rc7)
Generating Pods project
Integrating client project

ライブラリの意味は、地味に覚えるしか無い。

xcodeに表示された。

xcode

Objective-C リモートJSON解析

2013年7月27日 Posted by PURGE

久しぶりに、Objective-C の復習。
JSONの解析には、最近は標準ライブラリの、NSJSONSerialization を使用するらしい。

    //URL生成
    NSURL *url = [NSURL URLWithString:@"http://server.host/users.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //HTTPメソッド設定
    [request setHTTPMethod:@"GET"];
    
    //リクエスト送信
    NSHTTPURLResponse *response;
    NSError *error = nil;
    NSData *jsonData = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&response
                                                      error:&error];
    if(!error)
    {
        //JSON解析
        NSLog(@"status code: %d", [response statusCode]);
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingAllowFragments
                                                                  error:&error];
        
        for (NSDictionary *dict in jsonDict)
        {
            NSLog(@"%@ %@", [dict objectForKey:@"last_name"],[dict objectForKey:@"first_name"]);
        }
    }else{
        NSLog(@"error: %@", error);
    }

WindowベースアプリとViewベースアプリ

2010年7月2日 Posted by PURGE

WindowベースアプリとViewベースアプリの違いは、Viewベースアプリの場合は、ViewControllerを使用している点です。

WindowAppDelegate.h

@interface WindowAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
@property(nonatomic, retain) IBOutlet UIWindow *window;
@end

ViewAppDelegate.h

@class ViewAppViewController;
@interface ViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ViewAppController *viewController;
}
@property(nonatomic, retain) IBOutlet UIWindow *window;
@property(nonatomic, retain) IBOutlet ViewAppViewController *viewController;
@end

ViewAppViewController.m

-(BOOL)application:(UIApplication *)allication didFinishLanchingWithOptions:(NSDictionary *)lanchOptions{
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
-(void)dealloc{
[viewController release];
[window release];
[super dealloc];
}