Sending a message to nil in Objective-C -


as java developer reading apple's objective-c 2.0 documentation: wonder "sending message nil" means - let alone how useful. taking excerpt documentation:

there several patterns in cocoa take advantage of fact. value returned message nil may valid:

  • if method returns object, pointer type, integer scalar of size less or equal sizeof(void*), float, double, long double, or long long, message sent nil returns 0.
  • if method returns struct, defined mac os x abi function call guide returned in registers, message sent nil returns 0.0 every field in data structure. other struct data types not filled zeros.
  • if method returns other aforementioned value types return value of message sent nil undefined.

has java rendered brain incapable of grokking explanation above? or there missing make clear glass?

i idea of messages/receivers in objective-c, confused receiver happens nil.

well, think can described using contrived example. let's have method in java prints out of elements in arraylist:

void foo(arraylist list) {     for(int = 0; < list.size(); ++i){         system.out.println(list.get(i).tostring());     } } 

now, if call method so: someobject.foo(null); you're going nullpointerexception when tries access list, in case in call list.size(); now, you'd never call someobject.foo(null) null value that. however, may have gotten arraylist method returns null if runs error generating arraylist someobject.foo(otherobject.getarraylist());

of course, you'll have problems if this:

arraylist list = null; list.size(); 

now, in objective-c, have equivalent method:

- (void)foo:(nsarray*)anarray {     int i;     for(i = 0; < [anarray count]; ++i){         nslog(@"%@", [[anarray objectatindex:i] stringvalue];     } } 

now, if have following code:

[someobject foo:nil]; 

we have same situation in java produce nullpointerexception. nil object accessed first @ [anarray count] however, instead of throwing nullpointerexception, objective-c return 0 in accordance rules above, loop not run. however, if set loop run set number of times, we're first sending message anarray @ [anarray objectatindex:i]; return 0, since objectatindex: returns pointer, , pointer 0 nil/null, nslog passed nil each time through loop. (although nslog function , not method, prints out (null) if passed nil nsstring.

in cases it's nicer have nullpointerexception, since can tell right away wrong program, unless catch exception, program crash. (in c, trying dereference null in way causes program crash.) in objective-c, instead causes possibly incorrect run-time behavior. however, if have method doesn't break if returns 0/nil/null/a zeroed struct, saves having check make sure object or parameters nil.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -