Dumping contents of Array Obj-c to consoler

白昼怎懂夜的黑 提交于 2020-01-14 02:47:13

问题


I looked for how to dump and array to the console I have mostly found:

for (id name in arrayStuff)
    NSLog (@"Array contents:  %d", name);

I've tried different formaters %d %@ %g etc. which does print different stuff, but not the values I'm 99% sure are being entered into the object and consequently the array. This doesn't seem to work, how would you know what to use as the formater?

I have an NSMutableArray with instance of an object containing one int and two doubles added to the array in each loop. I would like to print those values out and make sure the correct ones are going in. Any ideas?

Thanks


回答1:


Your format specifier is wrong. NSArrays contain objects, not ints, so you have to use the specifier for Objective-C objects %@:

for (id name in arrayStuff)
    NSLog(@"Array element: %@", name);

Or just:

NSLog(@"Array contents: %@", arrayStuff);



回答2:


You want to use the "%@" format specifier for printing objects.

To have the contents of your object displayed (the int & doubles), you need to implement the -description method in your object.

See What is the Objective-C equivalent for "toString()", for use with NSLog?




回答3:


If you've created an Object type to hold the values, then use that object type in your for loop, and then use the getter to access the objects:

for (ObjectName name in arrayStuff) {
    NSLog(@"Array int: %d", name.myIntValue);
    NSLog(@"Array double: %f ...
}


来源:https://stackoverflow.com/questions/4071124/dumping-contents-of-array-obj-c-to-consoler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!