我用这个答案将 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;
}
但是当我在单元格中加载图像时无法解码字符串,因为它有一个空值,并且应用程序崩溃了!
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[_NSPlaceholderData initWithBase64EncodedString:options:]: nil string argument'
我认为问题出在编码上,但我自己解决不了!
我哪里错了?
谢谢
QUESTION UPDATE
Zaph 的问题是正确的,我尝试更好地解释: 我有一个空 TableView ,用户为每一行添加一个图像和一个文本字符串。 所以我尝试使用苹果官方的这个指南
在类 XYZToDoItem 中添加属性 @property NSString * itemName;我可以轻松添加用户创建的文本字符串。 但是我怎样才能在这个类中添加图像呢? 所以我想到将图像转换为字符串并添加一个属性@property NSString * imageString; 但出了点问题,我不能这么做! 你能建议一个更好的方法吗?
非常感谢您的支持和帮助!!
最佳答案
条件语句中的代码
if (! self.objects) { // true for self.objects == nil
[self.objects addObject: self.newData.imageString];
[self.tableView reloadData];
}
仅当self.objects
为nil
时才会执行。所以当self.objects
不存在时会调用self.tableView reloadData
,意思是
ObjectClass * object = [self.objects objectAtIndex: indexPath.row]; // object is nil
会将object
分配给nil
。
然后对 decodeBase64ToImage
的后续调用将失败,因为 object.imageString
为 nil
。
关于ios - UIImage 中的编码字符串返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456890/