Objective-Cのクラス・メモリ管理
メソッドの種類
- クラスメソッド
JAVA,.NETのstaticメソッドと同様、クラスいんんスタンスを生成しなくても使えるメソッド
+ (id) stringWithFormat: (NSString *) format
- ファクトリメソッド
クラスのインスタンスを生成する為のメソッド
一般にnew等、MakeConn....などの使い方をするメソッド。書き方はクラスメソッドと同じ
- インスタンスメソッド
一般に使うメソッド、インスタンスを生成してから、そのインスタンスを元として呼び出されるメソッド
- (NSString) userid:
NSString
- (BOOL) isEqualToString: *NSString *) aString;
- 使用例
NSString *thing1 = @"aaa"; if ([thing1 isEqualToString @"bbb"]) { .... }
- (NSComparisonResult) compare: (NSString *) string;
NSException raiseを追加
DEBUG中にエラーが発生した部分で止める方法
文字列を分解し配列化
splitと同じ処理
- componentsSeparatedByString:を使用
NSStringg *string = @"oop:ack:bork:greeble:ponies"; NSArray "chunks = [string componentsSeparatedByString: @":"];
配列を区切文字列を挿入した文字列にする
componentsJoinedByString:を使用
string = [chucks componentsJoinedByString: @","];
結果:"oop,ack,bork,greeble,ponies"
Mutable変数
メンバーを追加したり削除できle変数形
- NSMutableString
- stringWithCapacity
- appendString
- appendFormat
- deleteCharactersInRange
- NSMutableArray
- arrayWithCapacity
- addObject
- removeObjectAtIndex
削除オブジェクトの後ろに有るし全ての要素は、穴を埋めるためシフトされる
- NSDictionary
- dictionaryWithObjectAndKey
- objectForKey
- dictionaryWithCapacity
- setObject
- removeObjectForKey
配列の繰り返し処理
- NSEnumeratorを使用
NSEnumerator "enumtor enumtor = [array1 objectEnumerator]; id thing; while (thing = [enumtor nextObject]) { ... }
- ForEachの様に使う方法
NSEnumeratorより高速である
for (NSString "string in array1) { ... }
Objective-Cのメモリ管理
- retain, dealloc, release
- alloc,new,copyを行った場合は必ずreleaseを認識来する事
- AutoreleasePool
自動解放処理は完璧ではない為、必要によってプールるを再設定するなり、工夫が必要である
{ NSAutoreleasePool *pool; pool = [[NSAutoreleasePool alloc] init]; ..... [pool release]; }
- Garbage Collection
- Xcodeの[プロジェクト情報]ウィンドウの[ビルド]タブに行きObjective-C Garbage Collectionを[Required]にセットする
テキストフィールドの値を渡す場合は必ず「copy」を使う
テキストフィールドから手に入れた文字列は、一般にミュータブルな文字列はである為、
ユーザーが新しい文字列を入力すると変わってしまう。
引数として渡される文字列も同じく、ミュータブル文字列の場合、値が変わらない様に「copy」を使用する
- (void) setName: (NSString *) newName { [name release]; name = [newName copy]; }