我正在编写一个文本编辑器,用户可以使用它输入带有样式的文本并插入图像,所以我使用 NSAttributedString 来管理内容。我的问题是如何存储文本编辑器关闭之前的内容,并在下次打开编辑器后恢复内容?
我写了一个 NSAttributedString 类别,现在我可以在 NSTextAttachment 中存储(和恢复)文本但不能存储 UIImageView,下面是我的代码的一部分:
-(NSData*)customEncode {
__block NSMutableArray* archivableAttributes=[[NSMutableArray alloc]init];
[self enumerateAttributesInRange:NSMakeRange(0, [self length]) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
NSLog(@"range: %d %d",range.location, range.length);
NSLog(@"dict: %@",attrs);
NSLog(@"keys: %@", [attrs allKeys]);
NSLog(@"values: %@", [attrs allValues]);
NSMutableDictionary* tDict=[[NSMutableDictionary alloc]init];
[tDict setObject:[NSNumber numberWithInt:range.location] forKey:@"location"];
[tDict setObject:[NSNumber numberWithInt:range.length] forKey:@"length"];
for (NSString* tKey in [attrs allKeys]) {
if ([tKey isEqualToString:@"CTUnderlineColor"]) {
[tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTUnderlineColor"])] forKey:@"CTUnderlineColor"];
}
if ([tKey isEqualToString:@"NSUnderline"]) {
NSNumber* underline=[attrs objectForKey:@"NSUnderline"];
[tDict setObject:underline forKey:@"NSUnderline"];
}
if ([tKey isEqualToString:@"CTForegroundColor"]) {
[tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTForegroundColor"])] forKey:@"CTForegroundColor"];
}
if ([tKey isEqualToString:@"NSFont"]) {
CTFontRef font=((__bridge CTFontRef)[attrs objectForKey:@"NSFont"]);
NSDictionary* fontDict=[NSDictionary
dictionaryWithObjects:
[NSArray arrayWithObjects:(NSString*)CFBridgingRelease(CTFontCopyPostScriptName(font)),[NSNumber numberWithFloat:CTFontGetSize(font)], nil]
forKeys:
[NSArray arrayWithObjects:@"fontName", @"fontSize", nil]];
[tDict setObject:fontDict forKey:@"NSFont"];
}
}
[archivableAttributes addObject:tDict];
}];
NSMutableDictionary* archiveNSMString=[NSMutableDictionary
dictionaryWithObjects: [NSArray arrayWithObjects:[self string],archivableAttributes,nil]
forKeys:[NSArray arrayWithObjects:@"string",@"attributes",nil]];
NSLog(@"archivableAttributes array: %@",archiveNSMString);
NSData* tData=[NSKeyedArchiver archivedDataWithRootObject:archiveNSMString];
NSLog(@"tdata: %@",tData);
return tData;
}
我花了相当长的时间进行调查和实验,搜索显示有几个人有同样的问题,但没有令人满意的答案。