闲来无聊看了下iOS5编程,第一章是一个Hello World
不过由于书上是以xcode 4.2为基础讲的,和4.3区别很大,我也懒得去研究了。
看第二章吧,讲讲Objectve-C的一些基础知识,看着也没啥吃力的,随便翻了下。
以一个RandomPossession为例子讲的OC的类的创建和一些操作,比如传递消息什么的,和函数调用类似。
Possession.h
#import <Foundation/Foundation.h> @interface Possession : NSObject { NSString *possessionName; NSString *serialNumber; int valueInDollars; NSDate *dateCreated; } - (void)setPossessionName:(NSString *)str; - (NSString *)possessionName; - (void)setSerialNumber:(NSString *)str; - (NSString *)serialNumber; - (void)setValueInDollars:(int)i; - (int)valueInDollars; - (NSDate *)dateCreated; - (id)initWithPossessionName:(NSString *)name valueInDollars:(int)value serialNumber:(NSString *)sNumber; + (id)randomPossession; @end
Possession.m
#import "Possession.h" @implementation Possession - (void)setPossessionName:(NSString *)str { possessionName = str; } - (NSString *)possessionName { return possessionName; } - (void)setSerialNumber:(NSString *)str { serialNumber = str; } - (NSString *)serialNumber { return serialNumber; } - (void)setValueInDollars:(int)i { valueInDollars = i; } - (int)valueInDollars { return valueInDollars; } - (NSDate *)dateCreated { return dateCreated; } - (NSString *)description { NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d , recorded on %@", possessionName, serialNumber, valueInDollars, dateCreated]; return descriptionString; } - (id)initWithPossessionName:(NSString *)name valueInDollars:(int)value serialNumber:(NSString *)sNumber { self = [super init]; if(self){ [self setPossessionName:name]; [self setSerialNumber:sNumber]; [self setValueInDollars:value]; dateCreated = [[NSDate alloc] init]; } return self; } + (id)randomPossession { NSArray *randomAdjectiveList = [NSArray arrayWithObjects:@"Fluffy" , @"Rusty" , @"Shiny",nil]; NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",@"Spork" ,@"Mac" , nil]; int adjectiveIndex = rand() % [randomAdjectiveList count]; int nounIndex = rand() % [randomNounList count]; NSString *randomName = [NSString stringWithFormat:@"%@ %@", [randomAdjectiveList objectAtIndex:adjectiveIndex], [randomNounList objectAtIndex:nounIndex]]; int randomValue = rand() % 100; NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c", '0' + rand() % 10, 'A' + rand() % 26, '0' + rand() % 10, 'A' + rand() % 26, '0' + rand() % 10]; Possession *newPossession = [[self alloc] initWithPossessionName:randomName valueInDollars:randomValue serialNumber:randomSerialNumber]; return newPossession; } @end
main.m
#import <Foundation/Foundation.h> #import "Possession.h" int main(int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *items = [[NSMutableArray alloc] init]; for(int i = 0 ; i < 10 ; i++){ Possession *p = [Possession randomPossession]; [items addObject:p]; } for(Possession *item in items) NSLog(@"%@" ,item); [items release]; items = nil; } return 0; }
总的说对这个语言没啥特别的感觉,不过也不讨厌。