我想按字母顺序在表格视图中显示手机通讯录和图片。
我已设法以正确的顺序显示联系人姓名,但无法按正确顺序显示图片。
我已经尝试了几天,但没有成功。
我知道如何对数组进行排序,但不知道如何对图像数据进行排序。
请帮帮我们。
这是我的演示代码:
NSArray *sortedFirstNames;
- (void)getPersonDetails
{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil)
{
NSLog(@"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
NSMutableArray *firstNames = [[NSMutableArray alloc] init];
NSMutableArray *firstimages = [[NSMutableArray alloc] init];
for (i = 0; i < [allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName;
if (lastName == nil)
{
fullName = [NSString stringWithFormat:@"%@", firstName];
[firstNames addObject: fullName];
}
else if(firstName ==nil)
{
fullName = [NSString stringWithFormat:@"%@", lastName];
[firstNames addObject: fullName];
}
else
{
fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
[firstNames addObject: fullName];
}
person.firstName = firstName;
person.lastName = lastName;
person.fullName = fullName;
//email
imgdata=(__bridge NSData*)ABPersonCopyImageDataWithFormat(contactPerson, kABPersonImageFormatThumbnail);
NSLog(@"newstris%@",imageStr);
if(imgdata==nil)
{
}
else
{
[firstimages addObject:imgdata];
}
[self.tableData addObject:person];
}
sortedFirstNames = [firstNames sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
CFRelease(addressBook);
}
在单元格中显示图像的代码:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image1;
// cell.imageView.frame = CGRectMake(0, 0, 50, 50);
if (person.imgdata==nil) {
image1=[UIImage imageNamed:@"default_profile_pic.jpg"];
}
else
{
image1 = [UIImage imageWithData:person.imgdata];
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image1];
imageView.frame = CGRectMake(6.5, 6.5, 45., 45.);
dispatch_sync(dispatch_get_main_queue(), ^{
[cell addSubview:imageView];
});
});
谢谢..
答案 0 :(得分:1)
答案非常简单。
在Person
课程中添加一个存储NSData
的字段。
像:
@property (nonatomic, strong) NSData *imageData;
并使用:
person.imageData = imgdata;
答案 1 :(得分:0)
我也面临同样的问题。我已经通过像这样的关联对象解决了这个问题。
加载源数组时:
objc_setAssociatedObject(hDetails, @"imageUrl", record, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
在indexpath的行的单元格中:
Record *record = objc_getAssociatedObject(hDetails,@"imageUrl");
有关更多参考,请参阅:
How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?