2012-10-22 4 views
0

두 객체가 <MLBLeagueStandings: 0xeb2e4b0> 인 NSMutableArray 피드가 있습니다. 파일에 쓰고 파일에서 읽고 싶습니다. 이것은 내가 무엇을했는지 있습니다 :파일에 NSMutableArrray 쓰기 후

- (void)encodeWithCoder:(NSCoder *)encoder { 
    [encoder encodeObject:feed.leagues forKey:@"feed.leagues"]; 
} 

- (id)initWithCoder:(NSCoder *)decoder { 
    if (self = [super init]) { 
     self.feed.leagues = [decoder decodeObjectForKey:@"feed.leagues"]; 
    } 
    return self; 
} 

-(void)saveJSONToCache:(NSMutableArray*)leaguesArray { 
    NSString *cachePath = [self cacheJSONPath]; 

    [NSKeyedArchiver archiveRootObject:feed.leagues toFile:cachePath]; 
    NSMutableArray *aArray = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath]; 
    NSLog(@"aArray is %@", aArray); 
} 

-(NSString*)cacheJSONPath 
{ 

    NSString *documentsDirStandings = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *cacheJSONPath = [NSString stringWithFormat:@"%@/%@_Standings.plist",documentsDirStandings, sport.acronym]; 
return cacheJSONPath; 
} 
+0

당신이 직면 할 어떤 문제에 지정하십시오? 정확히 무엇을하고 싶은지 구체적으로 설명하십시오. – Krunal

+0

이 오류가 발생합니다. 2012-10-22 11 : 44 : 13.361 FOX Sports [60958 : 16d03] - [MLBLeagueStandings encodeWithCoder :] : 인스턴스로 전송 된 인식 할 수없는 선택기 0xee3d6c0 2012-10-22 11 : 44 : 13.362 FOX Sports [60958 : 16d03] *** 캐치되지 않은 예외 'NSInvalidArgumentException'으로 인해 응용 프로그램을 종료합니다. 이유 : '- [MLBLeagueStandings encodeWithCoder :] : 인스턴스 0xee3d6c0에 전송 된 인식 할 수없는 선택기' *** 처음 호출 스택을 throw합니다. [NSKeyedArchiver archiveRootObject : feed. leagues toFile : cachePath] – Manpreet

+0

@ Goti : 나는 feed.leagues 배열을 파일에 저장하고 앞으로 거기에서 그것을 읽고 싶다. 배열에 두 개의 MLBLeagueStandings 클래스 객체가 있습니다. – Manpreet

답변

1

개체 : MLBLeagueStandings가 직렬화하고 NSCoding의 protocole에 응답해야합니다

당신의 MLBLeagueStandings에서 지금
@interface MLBLeagueStandings : NSObject <NSCoding>{ 

} 

클래스 파일 (하는 .m) 다음과 같은 방법을 추가

- (id)initWithCoder:(NSCoder *)decoder; 
{ 
    self = [super initWithCoder:decoder]; 
    if(self) 
    { 
    yourAttribute = [decoder decodeObjectForKey:@"MY_KEY"] 
    //do this for all your attributes 
    } 
} 

- (void)encodeWithCoder:(NSCoder *)encoder; 
{ 
    [encoder encodeObject:yourAttribute forKey:@"MY_KEY"]; 
    //do this for all your attributes 
} 

실제로 파일에 개체를 쓰고 싶다면 (이 경우 배열입니다)이 배열에 포함 된 모든 개체는 NSCoding 프로토 콜을 준수해야합니다.

당신이 예를 원하는 또한 경우 :

here is a good tutorial 그것은 당신을 도울 것입니다 바랍니다.

NB : 당신은/디코딩 원시 형 인코딩하려는 경우 (지능, 부동 등) 사용

[encode encodeInt:intValue forKey:@"KEY"]; 

(more information on apple doc)

+0

int 또는 float 인 경우 encodeObject 또는 decodeObjectforKey에 객체를 추가하는 방법 – Manpreet

+0

[엔코더 encodeInt : intValue forKey : @ "MY_INT_KEY"];를 사용할 수 있습니다. apple 설명서에 대한 자세한 정보 : https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSCoder_Class/Reference/NSCoder.html – Ashbay