【发布时间】:2014-10-20 00:19:48
【问题描述】:
我使用这个答案将 UIImage 转换为 NSSstring,
https://stackoverflow.com/a/11251478/3741799
编码
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
解码
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
这里对图像进行编码并将 NSString 放在一个 NSObject 类中
self.newData.imageString = [self encodeToBase64String: image];
将新对象添加到 tableView
- (Void) insertNewObject: (id) sender {
if (! self.objects) {
[self.objects addObject: self.newData.imageString];
[self.tableView reloadData];
}
[self.objects InsertObject: self.newData atIndex: 0];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow: 0 inSection: 0];
[self.tableView insertRowsAtIndexPaths: @ [indexPath] withRowAnimation: UITableViewRowAnimationAutomatic];
}
然后在 TableView 中加载新对象!
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
static NSString * CellIdentifier = @ "Custom";
CustomCell * cell = (CustomCell *) [self.tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath];
ObjectClass * object = [self.objects objectAtIndex: indexPath.row];
cell.imageView.image = [self decodeBase64ToImage: object.imageString];
return cell;
}
但是当我在单元格中加载图像时无法解码字符串,因为它有一个空值,并且应用程序崩溃了!
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[_NSPlaceholderData initWithBase64EncodedString:options:]: nil 字符串参数'
我认为问题出在编码上,但我自己无法解决!
我哪里错了?
谢谢
问题更新
Zaph 的问题是对的,我试图更好地解释: 我有一个空表视图,用户为每一行添加一个图像和一个文本字符串。 所以我试着用苹果官方的这个指南
在类 XYZToDoItem 中添加属性 @property NSString * itemName;我可以轻松添加用户创建的文本字符串。 但是我怎样才能在这个类中添加图像呢? 所以我想将图像转换为字符串并添加一个属性@property NSString * imageString; 但是出了点问题,我不能那样做! 您能提出一个更好的方法吗?
非常感谢您的支持和帮助!!
【问题讨论】:
-
为什么要将
NSData转换为Base64 编码的NSString并返回?你想用这种编码/解码来完成什么? -
在
cellForRowAtIndexPath:中self.objects存在吗?在您的insertNewObject:方法中,您有一个 if 来检查 self.objects 是否为 nilif (! self.objects) {,如果是,它会在该 nil 上调用addObject:。我猜你想先创建self.objects,然后调用addObject:。 -
谢谢 Zaph,我已经更新了问题!!
标签: ios objective-c uitableview ios8 xcode6