6,爲BNREmployee添加一對多關係
一對多關係是由collection對象和包含的對象組成的,打開BNREmployee,創建一個新的實例變量,保存指向NSMutableArray對象指針。
BNREmployee.h
#import "BNRPerson.h"
@class BNRAsset;
@interface BNREmployee : BNRPerson
{
NSMutableArray *_assets;
}
@property(nonatomic)NSUInteger employeeID;
@property(nonatomic)NSUInteger officeAlarmCode;
@property(nonatomic)NSDate *hireDate;
@property(nonatomic,copy)NSArray *assets;
- (void)addAssets:(BNRAsset *)a;
- (unsigned int)valueOfAssets;
- (double)yearsOfEmployment;
@end
class的作用是告訴編譯器,有一個BNRAsset的類。
下面處理BNREmployee.m
#import "BNREmployee.h"
#import "BNRAsset.h"
@implementation BNREmployee
- (void)setAssets:(NSArray *)a
{
_assets=[a mutableCopy];
}
- (NSArray*)assets
{
return [_assets copy];
}
-(void)addAssets:(BNRAsset *)a
{
if(!_assets){
_assets=[[NSMutableArray alloc] init];
}
[_assets addObject:a];
}
- (unsigned int)valueOfAssets
{
unsigned int sum=0;
for(BNRAsset *a in _assets)
{
sum+=[a resaleValue];
}
return sum;
}
- (double)yearsOfEmployment
{
if(self.hireDate)
{
NSDate *now=[NSDate date];
NSTimeInterval seconds=[now timeIntervalSinceDate:self.hireDate];
return seconds/31557600.0;
}
else return 0;
}
- (CGFloat)BMI{
CGFloat normalbmi=[super BMI];
return normalbmi*0.9;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"employee %lu: $ %u in assets",self.employeeID,self.valueOfAssets];
}
- (void)dealloc
{
NSLog(@"deallocating %@",self);
}
@end
編輯main.m
#import <Foundation/Foundation.h>
#import "BNREmployee.h"
#import "BNRAsset.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *employees=[[NSMutableArray alloc] init];
for(int i=0;i<10;i++)
{
BNREmployee *mikey=[[BNREmployee alloc] init];
mikey.weightInKilo=90+i;
mikey.heightInMeters=1.8-i/10.0;
mikey.employeeID=i;
[employees addObject:mikey];
}
for(int i=0;i<10;i++)
{
BNRAsset *asset=[[BNRAsset alloc] init];
NSString *currentLable=[NSString stringWithFormat:@"Laptop %d",i];
asset.label=currentLable;
asset.resaleValue=350+i*17;
NSUInteger randomIndex=random()%[employees count];
BNREmployee *randomEmployee=[employees objectAtIndex:randomIndex];
[randomEmployee addAssets:asset];
}
NSLog(@"Employees: %@",employees);
NSLog(@"Giving up ownership of one employee");
[employees removeObjectAtIndex:5];
NSLog(@"Giving up ownership of arrays");
employees=nil;
}
return 0;
}
7,通過NSString 將數據寫入文件
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableString *str=[[NSMutableString alloc] init];
for(int i=0;i<10;i++){
[str appendString:@"liu is cool\n"];
}
[str writeToFile:@"/cool.txt"
atomically:YES
encoding:NSUTF8StringEncoding
error:NULL];
NSLog(@"done writing");
}
return 0;
}
下面認識一個NSError類,他進行了錯誤描述,聲明實例之後實參傳遞到writeToFile方法中如下。
如果寫入錯誤則會輸出錯誤描述。
8,NSString讀取文件
相應的也有讀文件
讀取我們剛剛保存的文件到字符串中,然後使用NSLog輸出。
9,NSData對象保存的數據寫入文件
在google網站上下載一張圖片,下載的數據保存在NSData實例中,二進制數寫入文件
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSURL *url=[NSURL URLWithString:@"//www.google.com/images/logos/ps_logo2.png"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSError *error;
NSData *data=[NSURLConnection sendSynchronousRequest:request
returningResponse:NULL
error:&error];
if(!data)
{
NSLog(@"failed :%@",[error localizedDescription]);
return 1;
}
NSLog(@"file has %lu bytes",(unsigned long)[data length]);
BOOL written=[data writeToFile:@"/tmp/g.png"
options:0
error:&error];
if(!written){
NSLog(@"write failed :%@",[error localizedDescription]);
}
NSLog(@"suceess!");
return 0;
}
writeToFile:optinos:error:方法保存設置通過option參數傳入。最常見的設置是使用NSDataWritingAtomic。
假設程序之前下載了一張圖片,現在正重新下載,則用新的文件替換舊的。如果覆蓋時斷電了,寫到一半的文件將會無法使用。如果要保證文件的完整性,應該使用具備原子性的寫操作。
在之前的代碼中 option:後面參數 把0改成NSDataWritingAtomic
現在NSData對象會先將數據寫入臨時文件,成功後再移動到指定的路徑。這樣系統要麼生成一個完整的文件,要麼什麼都沒有。
那麼同樣的,也可以從文件讀取數據創建NSData實例。
只要加入下面兩行
NSData *readData =[NSData dataWithContentsOfFile:@"/tmp/g.png"];
NSLog(@"the file read has %lu bytes",(unsigned long )[readData length]);