为什么我无法访问函数void AddressBookUpdated中的全局变量(ABAddressBookRef addressBook,CFDictionaryRef info,void * context)

时间:2014-03-29 05:28:48

标签: ios objective-c

我正在使用一个应用程序,我必须访问该地址簿。所有名称都在一个数组中。我正在使用的功能是:

#import "first.h"
#import <AddressBook/AddressBook.h>
@interface first ()
@property  (strong, nonatomic) NSMutableArray *data;

@end

@implementation first
@synthesize data;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
void AddressBookUpdated(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) {


  // NSMutableArray *data;
   //data=[[NSMutableArray alloc]init];
    ABAddressBookRevert(addressBook);
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    for ( int i = 0; i < nPeople; i++ )
{
    ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
    NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));


        NSString *combined = [NSString stringWithFormat: @"%@%@",
                              firstName, lastName];
        [data addObject:combined];//getting error "use of undeclared identifier 'date'"


}

我已经声明数据,因为你可以看到我的代码,但我仍然收到错误“使用未声明的'数据'”

1 个答案:

答案 0 :(得分:1)

组合不是一个全局变量 - 它是for循环块的本地变量。如果您希望它可用于您班级中的其他方法,那么您应该在.h文件中定义它,或者甚至更好地在.h文件中声明属性然后使用self。引用它。

e.g。

你的.h文件中的

@property  (strong, nonatomic) NSMutableArray *data;

然后在您的.m文件中

void AddressBookUpdated(ABAddressBookRef addressBook, CFDictionaryRef info, void *context) {

    self.data=[[NSMutableArray alloc]init];
    ABAddressBookRevert(addressBook);
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    for ( int i = 0; i < nPeople; i++ )
    {
        ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        NSString *combined = [NSString stringWithFormat: @"%@%@",
                              firstName, lastName];
        [self.data addObject:combined];
        NSLog(@"data is %@",data);

        kABPersonFirstNameProperty);
        //NSLog(@" name %@",combined);
    }
};