2013年5月26日 星期日

Objective-C 字串相加 (stringByAppendingString )

使用 stringByAppendingString:
#import <Foundation/Foundation.h>
int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *firstName = @"Wwfwwf";
    NSString *lastName = @"Liao";
    NSString *fullName = [[firstName stringByAppendingString: @" "] stringByAppendingString: lastName];
    NSLog(@"my name is %@\n", fullName);
    [pool drain];
    return 0;
}
result:
my name is Wwfwwf Liao
使用 stringWithFormat:
NSString *fullName = [NSString stringWithFormat: @"%@ %@", firstName, lastName];

Objective-C unsigned int ( NSUInteger )

輸出 NSUInteger,格式指定符為 %u 或是 %lu (long unsigned)
取得字串長度:
NSString *city = @"Taichung";
NSUInteger cityLength = [city length];
NSLog(@"City has %u characters", cityLength)
result:
City has 8 characters

數學運算:
NSNumber *price = [NSNumber numberWithInt: 20];
NSNumber *amount = [NSNumber numberWithInt: 6];

NSUInteger priceInt = [price unsignedIntValue];
NSUInteger amountInt = [amount unsignedIntValue];
NSUInteger total = priceInt * amountInt;

NSLog(@"Total price is %lu", total);
result:
Total price is 120
NSUInteger 的宣告無 * 符號

輸出 NSInteger,格式指定符為 %d 或是 %ld (long),取值訊息為 intValue

Objective-C 陣列 ( NSArray )

宣告一個 NSArray 物件,並透過傳遞 description 訊息給 NSArray 物件,印出陣列元素:
#import <Foundation/Foundation.h>

int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *foods =  [NSArray arrayWithObjects:@"tacos", @"burgers",nil];
    NSString *result = [foods description];

    NSLog(@"%@", result);
   
    [pool drain];
    return 0;
}
result:
(tacos, burgers)
陣列結尾須為 nil。

Objective-C 訊息傳遞 ( message passing )

在 C++ 裡呼叫方法,通常寫成:
myObj.method(argument);
或是:
myObj->method(argumennt);

而在 Objective-C裡,稱為傳遞訊息,語法為:
[myObj method: argument];