Getting object name in Objective-c

为君一笑 提交于 2019-12-10 19:29:12

问题


suppose i have a class Foo and an instance of this class myFoo:

Foo *myFoo;

is there any method "dispalyFooObjectName" that can display the name of the object, for exmample :

NSLog(@"i was called from %s", [myFoo dispalyFooObjectName]);

and the result will be :

i was called from myFoo

回答1:


In most programming languages objects don't have names. Just because some variable myFoo references your object, doesn't mean that your object is "called" myFoo.

And in most C-based languages variable names are not represented in the final executables at all (except for the names of external symbols).

So the short answer is that there's no way to get to that information.

If you want some "name", then you should add a name field to your Foo type.




回答2:


you can try this. override -(NSstring*)description method like this

- (NSString*)description {
     return [NSString stringWithFormat:@"I'm called from foo"];//You can also print object's properties description here.
  }

and use like this

 NSLog(@"my Foo object %@",[myFoo description]);


来源:https://stackoverflow.com/questions/5536724/getting-object-name-in-objective-c

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