如何打印NSSet的内容?

How to print the contents of NSSet?

我查询并获得了一个 NSSet,其中包含来自网络的客户地址。由于我是 objective c 开发的新手,我不知道如何从 set.So 中获取国家/地区、邮政编码等,我遵循了 Objective-C How to print NSSet on one line (no trailing comma / space),但我的输出是对象“0x7f99997b7a50”的形式”。如何打印集合中的所有字符串?提前致谢。

我这样试过

NSArray *ar = [customer.addresses allObjects]; 
for (int i = 0; i<ar.count; i++) 
{ 
    NSLog(@"arr %@",ar[i]); 
} 

但是输出是arr:

 <BUYAddress: 0x7fd451f6e050>

考虑下面的 NSSet,

 NSSet *theNSSet = [NSSet setWithObjects:@"Chennai",@"Mumbai",@"Delhi", nil];

使用

将其转换成NSArray
NSArray *array = [theNSSet allObjects]; // theNSSet is replaced with your NSSet id

然后打印出来

NSLog(@"%@",array);

我得到的输出

( Chennai, Delhi, Mumbai )

你的情况:

- (NSMutableSet *)addressesSet { 
 [self willAccessValueForKey:@"addresses"];
 NSMutableSet *result = (NSMutableSet *)[self mutableSetValueForKey:@"addresses"]; 
 [self didAccessValueForKey:@"addresses"];
 NSLog(@"%@",[result allObjects]); // printing the nsset 
 return result;
 } 

如果您有自定义对象,您可能需要覆盖 description

不覆盖:

-(void) testCustomObjects 
{
    CustomObject *co1 = [[CustomObject alloc] init];
    co1.name = @"James Webster";
    co1.jobTitle = @"Code Monkey";

    CustomObject *co2 = [[CustomObject alloc] init];
    co2.name = @"Holly T Canine";
    co2.jobTitle = @"Pet Dog";

    NSSet *set = [NSSet setWithObjects:co1, co2, nil];

    NSLog(@"%@", [set allObjects]);
}

产生:

2016-12-02 11:45:55.342 Playground[95359:4188387] (
    "<CustomObject: 0x600000037a20>",
    "<CustomObject: 0x60000003ae20>"
)

但是,如果我在 CustomObject class 中重写 description 方法:

-(NSString*) description
{
    return [NSString stringWithFormat:@"%@ (%@)", self.name, self.jobTitle];
}

我得到以下信息:

(
    "Holly T Canine (Pet Dog)",
    "James Webster (Code Monkey)"
)

如果由于某种原因,您无法添加描述方法,您只需要访问对象的相关部分;类似于以下内容:

NSArray *ar = [customer.addresses allObjects]; 
for (int i = 0; i<ar.count; i++) 
{ 
    NSLog(@"arr %@ (%@)",ar[i].name, ar[i].address); 
}

我已经略微查看了您正在使用的库。请尝试以下操作:

for (BUYAddress *address in customer.addresses)
{
    NSLog(@"Address: %@, %@, %@", address.address1, address.address2, address.city);
}