2016-06-03 3 views
3

NSDictionary을 쓸 수 없습니까 ?? 사전의 내용을 확인했습니다 : 모든 인스턴스는 NSStringNSNumber입니다. 나는 허가를 검사했다 : 동일한 경로에 동일한 이름을 가진 텍스트 파일이 잘 쓰여진다. 물론, 내 사전은 비어 있지 않습니다.개체가 유효한 동안 NSDictionary writeToFile이 실패합니다. 권한은 0입니다.

NSString *file = ... 
NSDictionary *dict = ... 

// check dictionary keys 
BOOL wrong = NO; 
for (id num in [dict allKeys]) { 
    if (![num isKindOfClass:[NSNumber class]]) { 
     wrong = YES; 
     break; 
    } 
} 
if (wrong) { 
    NSLog(@"First"); 
} 
// check dictionary values 
wrong = NO; 
for (id num in [dict allValues]) { 
    if (![num isKindOfClass:[NSString class]]) { 
     wrong = YES; 
     break; 
    } 
} 
if (wrong) { 
    NSLog(@"Second"); 
} 

if (![dict writeToFile:file atomically:YES]) { 
    // 0k, let's try to create a text file 
    NSLog(@"Names writing error!"); 
    [@"Something here... .. ." writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
} 

출력 : "이름 쓰기 오류!"
텍스트 파일이 성공적으로 만들어졌습니다.

+0

어디에서 씁니까? 번들에 있습니까? 적어도 iOS에서는 새로운 파일 경로에 글을 써야합니다. – Larme

+0

@Larme 바탕 화면의 폴더, Mac OS. –

답변

1

@vadian에서 지적한 것처럼 숫자 키로 plist를 작성할 수 없습니다.

NSURL *documents = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:false error:nil]; 
NSURL *fileURL = [documents URLByAppendingPathComponent:@"test.plist"]; 

// this will not work 

NSDictionary *dictionary = @{@1: @"foo", @2: @"bar"}; 
BOOL success = [dictionary writeToFile:fileURL.path atomically:true]; 
NSLog(@"plist %@", success ? @"success" : @"failure"); 

// this will 

fileURL = [documents URLByAppendingPathComponent:@"test.bplist"]; 
success = [NSKeyedArchiver archiveRootObject:dictionary toFile:fileURL.path]; 
NSLog(@"archive %@", success ? @"success" : @"failure"); 

을 그리고 당신은 NSKeyedUnarchiver 그것을 다시 읽을 수 있습니다 :하지만 당신은 NSKeyedArchiver을 사용할 수 있습니다

// to read it back 

NSDictionary *dictionary2 = [NSKeyedUnarchiver unarchiveObjectWithFile:fileURL.path]; 
NSLog(@"dictionary2 = %@", dictionary2); 

주, 당신은 NSCoding가 준수 (제대로 구현) 모든 클래스와 함께이 작업을 수행 할 수 있습니다. 다행히도 NSDictionary이 이미 준수합니다. 사전에있는 객체가 모두 일치하는지 확인해야합니다 (NSStringNSNumber 모두 해당). 사전에 사용자 지정 개체가있는 경우 올바르게 맞춤 설정해야합니다.

이것은 모두 Archives and Serializations Programming Guide에 설명되어 있습니다.

+0

코드가 간단하고 잘 작동합니다. 감사합니다. :) –

3

사전을 작성하면 속성 목록이 생성되고 documentation에 따르면 속성 목록의 모든 키는 문자열이어야합니다.

... NSDictionary와와 CFDictionary 객체 키가 문자열 객체가 아닌 경우, 모든 유형의 객체가 될 에 열쇠를 할 수 있지만, 컬렉션은 재산 목록 개체 수 없습니다.

NSNumber 키와 같은 개체는 지원되지 않습니다.