2012-04-05 2 views
0

다른 클래스에서 호출 한 내 plist 용 컨트롤러 클래스를 작성하고 있습니다. 컨트롤러 클래스는 읽기 및 저장 메소드를 가지고 있으며, 읽기 메소드는 plist를 열고 읽기 및 쓰기를 위해 문서 파일에 저장합니다. 이 읽기 클래스에서는 이전에 저장 한 모든 값을 자신의 변수에 넣습니다.plist에 저장하기 전에 값을 잃는 변수

다른 클래스에서 호출되는 Save 메서드 호출에서 모든 값이 매개 변수로 전달 된 다음 올바른 값으로 새 값을 전달하고이를 plist로 전달합니다. 그러나 사전 내 plist 내 유일한 값을 절약하고 null로 다른 재설정 .. 어떻게 이러한 변수가 자신의 가치를 지키도록해야합니까 궁금해?

가 여기 내 .H

#import <Foundation/Foundation.h> 

@interface EngineProperties : NSObject { 

NSString *signature; 
NSNumber *version; 
NSNumber *request; 
NSNumber *dataVersion; 
NSMutableDictionary *cacheValue; 
//cachevalue Items 
NSNumber *man; 
NSNumber *mod; 
NSNumber *sub; 

} 

@property (copy, nonatomic) NSString *signature; 
@property (copy, nonatomic) NSNumber *version; 
@property (copy, nonatomic) NSNumber *request; 
@property (copy, nonatomic) NSNumber *dataVersion; 
@property (copy, nonatomic) NSMutableDictionary *cacheValue; 
//cachevalue Items 
@property (copy, nonatomic) NSNumber *man; 
@property (copy, nonatomic) NSNumber *mod; 
@property (copy, nonatomic) NSNumber *sub; 



- (void) readPlistData; 
- (void) saveData:(NSString *)methodName signature:(NSString *)pSignature Version:(NSNumber *)pVersion request:(NSNumber *)rNumber dataVersion:(NSNumber *)dvReturned cacheValue:(NSNumber *)cValue; 

@end 

이며, 여기 내하는 .m

#import "EngineProperties.h" 

@implementation EngineProperties 

@synthesize signature; 
@synthesize version; 
@synthesize request; 
@synthesize dataVersion; 
@synthesize cacheValue; 

@synthesize man; 
@synthesize mod; 
@synthesize sub; 



//This opens up and reads the current plist ready to be used 
-(void) readPlistData 
{ 
    // Data.plist code 
    // get paths from root direcory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"]; 

    // check to see if Data.plist exists in documents 
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) 
    { 
     // if not in documents, get property list from main bundle 
     plistPath = [[NSBundle mainBundle] pathForResource:@"EngineProperties" ofType:@"plist"]; 
    } 

    // read property list into memory as an NSData object 
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 
    NSString *errorDesc = nil; 
    NSPropertyListFormat format; 
    // convert static property liost into dictionary object 
    NSDictionary *tempRoot = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; 
    if (!tempRoot) 
    { 
     NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); 
    } 
    // assign values 
    self.signature = [tempRoot objectForKey:@"Signature"]; 
    self.version = [tempRoot objectForKey:@"Version"]; 
    self.request = [tempRoot objectForKey:@"Request"]; 
    self.dataVersion = [tempRoot objectForKey:@"Data Version"]; 

    man = [cacheValue objectForKey:@"Man"]; 
    mod = [cacheValue objectForKey:@"Mod"]; 
    sub = [cacheValue objectForKey:@"SubMod"]; 

    cacheValue = [tempRoot objectForKey:@"Cache Value"]; 
} 


- (void) saveData:(NSString *)methodName signature:(NSString *)pSignature Version:(NSNumber *)pVersion request:(NSNumber *)rNumber dataVersion:(NSNumber *)dvReturned cacheValue:(NSNumber *)cValue; 
{ 
    // get paths from root direcory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"]; 

    // set the variables to the values in the text fields 
    self.signature = pSignature; 
    self.version = pVersion; 
    self.request = rNumber; 
    self.dataVersion = dvReturned; 

    //do some if statment stuff here to put the cache in the right place or what have you. 
    if (methodName == @"manufacturers") 
    { 
     self.man = cValue; 
    } 
    else if (methodName == @"models") 
    { 
     self.mod = cValue; 
    } 
    else if (methodName == @"subMod") 
    { 
     self.sub = cValue; 
    } 

    self.cacheValue = [NSDictionary dictionaryWithObjectsAndKeys: 
         man, @"Manufacturers", 
         mod, @"Models", 
         sub, @"SubModels", nil]; 


    NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys: 
           signature, @"Signature", 
           version, @"Version", 
           request, @"Request", 
           dataVersion, @"Data Version", 
           cacheValue, @"Cache Value", nil]; 



    NSString *error = nil; 
    // create NSData from dictionary 
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; 

    // check is plistData exists 
    if(plistData) 
    { 
     // write plistData to our Data.plist file 
     [plistData writeToFile:plistPath atomically:YES]; 

     NSString *myString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding]; 
     //  NSLog(@"%@", myString); 
    } 
    else 
    { 
     NSLog(@"Error in saveData: %@", error); 
     //  [error release]; 
    } 
} 


@end 

나는이 세 바르 올바른 값을 유지하는 방법을 찾기 위해 노력하고있다, 사람, 모드, 하위 그래서 나는 그들을 내 캐시 값 사전에 넣을 수 있습니다 ..

답변

2

문제는 사전을 만들 준비가 된 데이터를 얻는 것입니다 :

if (methodName == @"manufacturers") 
{ 
    self.man = cValue; 
} 
else if (methodName == @"models") 
{ 
    self.mod = cValue; 
} 
else if (methodName == @"subMod") 
{ 
    self.sub = cValue; 
} 

이 대신이 사용한다, 문자열을 비교하는 올바른 방법 (실제로 그래서 그들은 아마도 동일하지 않습니다 문자열의 주소를 비교하는)되지 않습니다 :

if ([methodName isEqualToString:@"manufacturers"]) 
{ 
    self.man = cValue; 
} 
else if ([methodName isEqualToString:@"models"]) 
{ 
    self.mod = cValue; 
} 
else if ([methodName isEqualToString:@"subMod"]) 
{ 
    self.sub = cValue; 
} 

또 다른 문제입니다 readPlistData에서 "Man", "Mod"및 "SubMod"키를 읽지 만 "Manufacturers", "Models"및 "SubModels"와 같이 사전에 쓰는 것과 동일해야합니다. (어느 쪽이 맞을 수도 있지만 동일한 키를 읽고 쓰는 데 일치해야합니다!)

마지막으로 으로 전화를 걸거나 새 번호를 만들 때마다 EngineProperties의 동일한 인스턴스를 사용하고 있습니까? 매번 객체가 필요합니까? 동일한 객체를 사용하지 않는 경우 iVars는 호출 할 때마다 nil로 재설정됩니다. 모든

+0

문자열 값을 비교하는 this를 참조하십시오 내가 3 개의 변수를 기록한 직후에 각 호출에 대한 문장이있다. check ---> 245442 (null) (null) check ---> (null) 140211 (null) check ---> (null) (null) (null) 9276 –

+0

saveData를 호출 할 때마다 내 첫 번째 방법으로 설정 한 나의 vars가 지워집니다. 저는 아마도 각각의 경우에 이전 값으로 다른 변수를 설정해야한다고 생각합니다. –

+0

업데이트 된 답변의 맨 아래에있는 다른 두 가지 문제를 참조하십시오. – lnafziger

0

먼저

- (void) saveData:(NSString *)methodName signature:(NSString *)pSignature Version:(NSNumber *)pVersion request:(NSNumber *)rNumber dataVersion:(NSNumber *)dvReturned cacheValue:(NSNumber *)cValue; 

를 호출 내가 .. 이런 것을 변경,하지만 난 여전히 같은 문제가 발생하고있다 않았다

//This opens up and reads the current plist ready to be used 
-(void) readPlistData 
{ 
    // Data.plist code 
    // get paths from root direcory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"]; 

    // check to see if Data.plist exists in documents 
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) 
    { 
     // if not in documents, get property list from main bundle 
     plistPath = [[NSBundle mainBundle] pathForResource:@"EngineProperties" ofType:@"plist"]; 
    } 

    // read property list into memory as an NSData object 
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 
    NSString *errorDesc = nil; 
    NSPropertyListFormat format; 
    // convert static property liost into dictionary object 
    NSDictionary *tempRoot = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc]; 
    man = [cacheValue objectForKey:@"Man"]; 
    mod = [cacheValue objectForKey:@"Mod"]; 
    sub = [cacheValue objectForKey:@"SubMod"]; 
    if (tempRoot && [tempRoot count]){ 
     // assign values 
     self.signature = [tempRoot objectForKey:@"Signature"]; 
     self.version = [tempRoot objectForKey:@"Version"]; 
     self.request = [tempRoot objectForKey:@"Request"]; 
     self.dataVersion = [tempRoot objectForKey:@"Data Version"]; 
     cacheValue = [tempRoot objectForKey:@"Cache Value"]; 
    } 

} 


- (void) saveData:(NSString *)methodName signature:(NSString *)pSignature Version:(NSNumber *)pVersion request:(NSNumber *)rNumber dataVersion:(NSNumber *)dvReturned cacheValue:(NSNumber *)cValue 
{ 
    // get paths from root direcory 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
    // get documents path 
    NSString *documentsPath = [paths objectAtIndex:0]; 
    // get the path to our Data/plist file 
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"]; 

    // set the variables to the values in the text fields 
    self.signature = pSignature; 
    self.version = pVersion; 
    self.request = rNumber; 
    self.dataVersion = dvReturned; 

    //do some if statment stuff here to put the cache in the right place or what have you. 
    if (methodName isEqualToString:@"manufacturers") { 
     self.man = cValue; 
    } else if (methodName isEqualToString:@"models") { 
     self.mod = cValue; 
    } else if (methodName isEqualToString:@"subMod") { 
     self.sub = cValue; 
    } 

    self.cacheValue = [NSDictionary dictionaryWithObjectsAndKeys: 
        man, @"Manufacturers", 
        mod, @"Models", 
        sub, @"SubModels", nil]; 


    NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys: 
          signature, @"Signature", 
          version, @"Version", 
          request, @"Request", 
          dataVersion, @"Data Version", 
          cacheValue, @"Cache Value", nil]; 



    NSString *error = nil; 
    // create NSData from dictionary 
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error]; 

    // check is plistData exists 
    if(plistData) { 
     // write plistData to our Data.plist file 
     [plistData writeToFile:plistPath atomically:YES]; 

     NSString *myString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding]; 
     //  NSLog(@"%@", myString); 
    } else { 
      NSLog(@"Error in saveData: %@", error); 
      // [error release]; 
    } 
} 
@end 
+0

나는 지금 내 대답을 편집했고, 단지 미성년자로 바꿨다. –

+0

덕분에 나는 그것을 구현하려고 시도하고 변수에 cValue를 전달하는 if 문과 함께 오류가 발생합니다. ** 기대되는 '**'** 그들은 squar bracket을 가지고 있다고 생각하지 않습니까? –

+0

글쎄 그게 문제가되지 않아, 난 그냥 거기에 체크 : (NSNumber *) cValue **; ** '저장'메서드 정의, 그래서 난 그냥 끝에 세미콜론을 제거하고 대답을 편집했습니다. ** **] ** 개폐를 놓친 것일 수도 있습니다. 나를 보여줘. –