2011年5月29日 星期日

Foundation Framework-歸檔 -CH19- 11 利用archiver 來做深層複製

// 利用archiver 來做深層複製

int main(int argc, char *argv[])

{

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSData *data;

NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:

[NSMutableString stringWithString:@"one"],

[NSMutableString stringWithString:@"two"],

[NSMutableString stringWithString:@"three"],

nil];

NSMutableArray *dataArray2;

NSMutableString *mstr;

// Make a deep copy using the archiver 利用archiver 來做深層複製

data = [NSKeyedArchiver archivedDataWithRootObject: dataArray];

dataArray2 = [ NSKeyedUnarchiver unarchiveObjectWithData:data]; // = dataArray2 = [ NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject: dataArray]];

mstr= [ dataArray2 objectAtIndex:0];

[mstr appendString:@"one"];

NSLog(@"dataArray: ");

for( NSString *elem in dataArray)

NSLog(@"%@", elem);

NSLog(@"\ndataArray2: ");

for(NSString *elem in dataArray2 )

NSLog(@"%@", elem);

[pool drain];

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}

Foundation Framework-歸檔 -CH19-9,10 NSData 三變數歸檔取出

//三種實體變數進行編碼,解碼


@interface Foo: NSObject

{

// 實體變數 : String ; int ; float

NSString *strval;

int intval;

float floatval;

}


// 此類別包含setter *1 ; getter*3 ; 用來編解碼 archive * 2

@property (copy, nonatomic) NSString *strVal;

@property int intVal;

@property float floatVal;


@end


@implementation Foo

@synthesize strVal, intVal, floatVal;


-(void) encodeWithCoder: (NSCoder *) encoder

{

[encoder encodeObject: strVal forKey: @"FoostrVal"];

[encoder encodeInt: intVal forKey: @"FoointVal"];

[encoder encodeFloat:floatVal forKey:@"FoofloatVal"];

}


-(id) initWithCoder: (NSCoder *) decoder

{

strVal = [[ decoder decodeObjectForKey: @"FoostrVal"] retain];

intVal = [decoder decodeIntForKey:@"FoointVal"];

floatVal = [ decoder decodeFloatForKey:@"FoofloatVal"];

return self;

}

@end


#import

#import

#import

#import

#import

#import

int main(int argc, char *argv[])

{

// 先將物件建立

NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc] init];

Foo *myFoo1= [[Foo alloc] init];

Foo *myFoo2;

NSMutableData *dataArea;

NSKeyedArchiver *archiver;

NSKeyedUnarchiver *unarchiver;

// in myBook containing four address cards

[myFoo1 setStrVal: @"This is the string"];

[myFoo1 setIntVal: 12345];

[myFoo1 setFloatVal: 98.6];

NSLog(@"init foo1 : %@\n%i\n%g",[myFoo1 strVal],[myFoo1 intVal],[myFoo1 floatVal]);

// Set up a data area and connect it to an NSKeyedArchiver object

dataArea = [ NSMutableData data];

archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: dataArea];

// Now we can begin to archived data to a file

[archiver encodeObject: myFoo1 forKey: @"myfoo1"];

[archiver finishEncoding];

// Write the archived data area to a file

if([dataArea writeToFile:@"myarchive" atomically:YES] ==NO){

NSLog(@"Archiving failed");

}

dataArea=[NSData dataWithContentsOfFile: @"myArchive"];

if(!dataArea) {

NSLog(@"Can't read back archive file!");

return 1;

}

unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:dataArea];

// Decode the Objects we previous stored

myFoo2 = [ unarchiver decodeObjectForKey: @"myfoo1"];

[unarchiver finishDecoding];

[archiver release];

// Verify that the restore was successful

NSLog(@"%@\n%i\n%g",[myFoo2 strVal],[myFoo2 intVal],[myFoo2 floatVal]);


[myFoo1 release];

//[myFoo2 release];

[pool drain];

return 0;

}


Foundation Framework-歸檔 CH19-8 keyed archive 編碼與解碼方法-三變數歸檔取出


//三種實體變數進行編碼,解碼


@interface Foo: NSObject

{

// 實體變數 : String ; int ; float

NSString *strval;

int intval;

float floatval;

}


// 此類別包含setter *1 ; getter*3 ; 用來編解碼 archive * 2

@property (copy, nonatomic) NSString *strVal;

@property int intVal;

@property float floatVal;


@end


@implementation Foo

@synthesize strVal, intVal, floatVal;


-(void) encodeWithCoder: (NSCoder *) encoder

{

[encoder encodeObject: strVal forKey: @"FoostrVal"];

[encoder encodeInt: intVal forKey: @"FoointVal"];

[encoder encodeFloat:floatVal forKey:@"FoofloatVal"];

}


-(id) initWithCoder: (NSCoder *) decoder

{

strVal = [[ decoder decodeObjectForKey: @"FoostrVal"] retain];

intVal = [decoder decodeIntForKey:@"FoointVal"];

floatVal = [ decoder decodeFloatForKey:@"FoofloatVal"];

return self;

}

@end


#import

#import

#import

#import

int main(int argc, char *argv[])

{

// 先將物件建立

NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc] init];

Foo *myFoo1= [[Foo alloc] init];

Foo *myFoo2;


[myFoo1 setStrVal: @"This is the string"];

[myFoo1 setIntVal: 12345];

[myFoo1 setFloatVal: 98.6];

// 歸檔

[NSKeyedArchiver archiveRootObject:myFoo1 toFile: @"foo.arch"];

// 取回

myFoo2= [NSKeyedUnarchiver unarchiveObjectWithFile:@"foo.arch"];

NSLog(@"%@\n%i\n%g", [myFoo2 strVal], [myFoo2 intVal], [myFoo2 floatVal]);

[myFoo1 release];

[pool drain];

return 0;

}

Foundation Framework-歸檔 CH19-7 keyed archive 編碼與解碼方法. main-讀出

#import "AddressBook.h"

#import


int main(int argc, char *argv[])

{

AddressBook *myBook;

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

myBook=[NSKyedUnarchiver unarchiveObjectWithFile: @"addresbook.arch"];

[myBook list];

[pool drain];

return 0;

}

Foundation Framework-歸檔 CH19-6 keyed archive 編碼與解碼方法-Main

int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

NSString *aName=@"Jason Huang";

NSString *aEmail=@"jason.huang@hotmail.com";

NSString *bName=@"Sharon Kang";

NSString *bEmail=@"sharon.kang@hotmail.com";

NSString *cName=@"Julia Lin";

NSString *cEmail=@"julia.lin@hotmail.com";

NSString *dName=@"Irene Huang";

NSString *dEmail=@"irene.huang@hotmail.com";

AddressCard *card1=[[AddressCard alloc] init];

AddressCard *card2=[[AddressCard alloc] init];

AddressCard *card3=[[AddressCard alloc] init];

AddressCard *card4=[[AddressCard alloc] init];

AddressBook *myBook=[AddressBook alloc];

//First set up four address cards

[card1 setName: aName andEmail: aEmail];

[card2 setName: bName andEmail: bEmail];

[card3 setName: cName andEmail: cEmail];

[card4 setName: dName andEmail: dEmail];

//Now initialize the address book

myBook =[myBook initWithName:@"Joe's address book"];

//Add some cards to the address book

[myBook addcard:card1];

[myBook addcard:card2];

[myBook addcard:card3];

[myBook addcard:card4];

[myBook sort];

if([NSKeyedArchiver archiveRootObject: myBook toFile: @"addrbook.arch"]==NO)

NSLog(@"archiving failed");

[card1 release];

[card2 release];

[card3 release];

[card4 release];

[myBook release];

[pool drain];

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}


Foundation Framework-歸檔 CH19-5 keyed archive 編碼與解碼方法

#import

#import

#import


@interface AddressCard : NSObject //使用NSCoding, NSCopyin 協定

{

NSString *name;

NSString *email;

}


//以下的兩個屬性(attribute)

// Copy : 表示setter中複製一個實體變數 ( ch15-18中預設為不要複製,這裡是先改變屬性為assign)

// Nonatomic :表示getter在回傳值前不可保留(retain)或自動釋放變數(autorelease )實體變數


@property (copy, nonatomic) NSString *name, *email;

-(void) setName:(NSString *) name andEmail:(NSString *) email;

-(void) print;

-(NSComparisonResult) compareNames: (id) element;


//Additional methodes for NSCopying protocol

-(AddressCard *) copyWithZone: (NSZone *) zone;

-(void) retainName: (NSString *) theName andEmail: (NSString *) theEmail;


@end

2011年5月21日 星期六

Foundation Framework-歸檔 CH19-3,4 NSKeyedArchiver & NSKeyedUnarchiver

// 寫入檔案

// main.m

// CH19-3 NSKeyArchiver

//

// Created by jason on 2011/5/21.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//


//#import

#import

#import

#import

#import

#import


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

NSDictionary *glossary= [ NSDictionary dictionaryWithObjectsAndKeys: @"Apple Inc. is an American multinational corporation that designs and markets consumer electronics, computer software, and personal computers.", @"Apple Inc.",

@"Steven Paul ""Steve"" Jobs (born February 24, 1955) is an American business magnate and inventor. He is the co-founder and chief executive officer of Apple Inc.", @"Steve Jobs",

@"The Macintosh, or Mac, is a series of several lines of personal computers designed, developed, and marketed by Apple Inc.",@"Macintosh",nil];

[NSKeyedArchiver archiveRootObject:glossary toFile:@"glossary.archive"]; // 寫入檔案 glossary.archive中

[pool release];

return 0;

// return NSApplicationMain(argc, (const char **) argv);

}

*******************************************************

//讀取檔案

// main.m

// CH19-4 NSKeyedUnarchiver

//

// Created by jason on 2011/5/21.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//


//#import

#import

#import

#import

#import

#import

#import


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

NSDictionary *glossary;

glossary = [NSKeyedUnarchiver unarchiveObjectWithFile:@"glossary.archive"];

for(NSString *key in glossary)

NSLog(@"%@: %@", key, [ glossary objectForKey:key]);//讀取檔案

[pool drain];

return 0;

// return NSApplicationMain(argc, (const char **) argv);

}


2011年5月19日 星期四

Foundation Framework-歸檔 CH19-2 read XML Property List

//

// main.m

// CH19-2 read property lists

//

// Created by jason on 2011/5/19.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//


//#import

#import

#import

#import

#import

#import


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

NSDictionary *glossary;

glossary=[NSDictionary dictionaryWithContentsOfFile:@"glossary"];

for(NSString *key in glossary)

NSLog(@"%@: %@", key, [glossary objectForKey:key]);

[pool drain];

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}

Foundation Framework-歸檔 CH19-1 XML Property List

//

// main.m

// CH19-1 XML Property Lists

//

// Created by jason on 2011/5/18.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//

// 物件如果是 NSString , NSDictionary , NSArray , NSDate, NSData, NSNumber型態 可以使用writeToFile: atomically: 方法將資料寫入檔案

//

#import

#import

#import

#import


//#import


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];

NSDictionary *glossary=[NSDictionary dictionaryWithObjectsAndKeys:@"Apple Inc. is an American multinational corporation that designs and markets consumer electronics, computer software, and personal computers.", @"Apple Inc.",

@"Steven Paul ""Steve"" Jobs (born February 24, 1955) is an American business magnate and inventor. He is the co-founder and chief executive officer of Apple Inc.", @"Steve Jobs",

@"The Macintosh, or Mac, is a series of several lines of personal computers designed, developed, and marketed by Apple Inc.",@"Macintosh",nil];

if([glossary writeToFile:@"glossary" atomically:YES]==NO) // "writeToFile:atuimically:encoding: error: " 將辭典以property list 形式寫入檔案 glossary

// 參數 atomically :YES 表示寫入時會使用暫存檔,若寫到一半當機, 原始檔案不會不見!

NSLog(@"Save to file failed!");

[pool drain];

return 0;

// return NSApplicationMain(argc, (const char **) argv);

}

2011年5月18日 星期三

複製物件 - Setter 與 Getter

*****************************************************************

[newCard setName: newName];


- (void) setName: (NSString *) the Name // <= 這樣可能會有不小心被改到的危險

{

name= theName;

}

*****************************************************************

Copy的方式來做


- (void) setName:(NSString *) theName

{

name = [ theName copy];

} // <= 這樣就不怕了


*********************************************************

//再加上一條

- (void) setName: (NSString *) theName

{

[name autorelease]; // <=加上 autorelease 會將舊的值釋放掉

name= [ theName copy];

}

*********************************************************

//使用合成方法


@property (nonatomic, copy) NSString *name; // nonatomic => 不必使用mutex lock property 暫存器 ,lock住的話可以避免再多工環境下不會同時執行相同的程式碼

// atomic(預設) => 有保護

// nonatomic => 無保護 (執行效率較差)


synthesize 方法

============================================

-(void) setName: (NSString *) the Name

{

if(theName!=name){

[name release];

name=[theName copy];

}

}

*********************************************************

// Getter狀況下 ,則會先 retain 然後 autorelease 實體變數



*********************************************************

// 我們想要複製一個 immutable 的物件的實體變數,卻不想複製物件內容

-(AddressCard *) copyWithZone:(NSZone *) zone

{

AddressCard *newCard = [[ AddressCard allocWithZone: zone ] init];

[newCard retainName: name andEmail: email];

return newCard;

}


-(void) retainName: (NSString *) theName andEmail: (NSString *)theEmail

{

name = [ theName retain];// <= 這裡它沒有複製參數,只有保留 retain 實體變數

email = [ theEmail retain];

}

2011年5月17日 星期二

Foundation Framework-複製物件 CH18-3 Protocol

//

// main.m

// CH18-3 Copying Fractions

//

// Created by jason on 2011/5/17.

// Copyright 2011 __MyCompanyName__. All rights reserved.

//


//#import


// 使用copy方法需要實作 (NSCopying)中的1~2種方法


#import

#import


@interface Fraction:NSObject //<= 加上 NSCopying協定 protocol

{

int numerator;

int denominator;

}


@property int numerator, denominator;

- (void) print: (BOOL) needReduce;

- (void) setTo: (int) n over:(int) d;

- (double) converToNum;

- (Fraction *) add:(Fraction *)f;

- (Fraction *) subtract:(Fraction *)f;

- (Fraction *) multiply:(Fraction *)f;

- (Fraction *) divide:(Fraction *)f;

- (void) reduce;


@end


@implementation Fraction


@synthesize numerator,denominator;


- (void) setTo: (int) n over:(int) d{

numerator=n;

denominator=d;

}



- (void) print:(BOOL) needReduce{

if(needReduce)

[self reduce];

NSLog(@"the Fraction is %i/%i",numerator,denominator);

}


-(double) converToNum{

if(denominator!=0)

return (double)numerator/denominator;

else

return 1.0;

}


- (Fraction *) add:(Fraction *)f{

Fraction *result=[Fraction new];

int n,d;

if(denominator==0){

n=f.numerator;

d=f.denominator;

}else{

n=numerator*f.denominator+f.numerator*denominator;

d=denominator*f.denominator;

}

[result setTo:n over:d];

[result reduce];

return result;

}


- (Fraction *) subtract:(Fraction *)f{

Fraction *result=[Fraction new];

int n,d;

if (denominator==0){

n=f.numerator;

d=f.denominator;

[result setTo:n over:d];

}else{

n=numerator*f.denominator-f.numerator*denominator;

d=denominator*f.denominator;

[result setTo:n over:d];

[result reduce];

}

return result;

}

- (Fraction *) multiply:(Fraction *)f{

Fraction *result=[Fraction new];

int n,d;

if (denominator==0){

n=0;

d=0;

[result setTo:n over:d];

}else{

n=numerator*f.numerator;

d=denominator*f.denominator;

[result setTo:n over:d];

[result reduce];

}

return result;

}

- (Fraction *) divide:(Fraction *)f{

Fraction *result=[Fraction new];

int n,d,temp;

if (denominator==0){

n=0;

d=0;

[result setTo:n over:d];

}else{

temp=f.numerator;

f.numerator=f.denominator;

f.denominator=temp;

result=[self multiply:f];

[result reduce];

}

return result;

}


- (void) reduce{

int u=numerator;

int v=denominator;

int temp;

while(v!=0){

temp = u%v;

u=v;

v=temp;

}

numerator/=u;

denominator/=u;

}


-(id) copyWithZone: (NSZone *)zone // 為我們的參數配置記憶體區段

{

Fraction *newFract =[[Fraction allocWithZone:zone] init]; // 若這個類別為子類別 ,這裡要用 Fraction *newFract =[[[self class] allocWithZone:zone] init]; 我們新配置的物件方法來自於 copy的接收者

// 例如: 它是 Fraction 類別的子類別叫 NewFraction, 我們要在繼承的方法中配置一個 NewFraction的物件來取代 Fraction物件

// 若父類別已經實作了 ,我們要先呼叫父類別的 copy 方法 ,以複製繼承下來的實體變數 , 然後加上自己的code來加入新的實體變數

[newFract setTo: numerator over: denominator];

return newFract;

}

@end


int main(int argc, char *argv[])

{

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

Fraction *f1 = [[Fraction alloc] init];

Fraction *f2;

[f1 setTo:2 over:5];

f2 = [f1 copy];

[f2 setTo:1 over:3];

[f1 print: NO]; // => 2/5

[f2 print: NO]; // => 1/3 , f1&f2有各自獨立的記憶體空間

[f1 release];

[f2 release];

[pool drain];

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}