i’m trying to understand this in objective-c :
in this example, indexPath is a pointer but we use it “as is” in the function : indexPath.section, instead of (for example) *indexPath.section(with a *) :
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
return (indexPath.section == 0) ? nil : indexPath;
}
so, in objective-c, we don’t need to add a * to get the content of the variable where the pointer points to…?
but i found this function, where they use a * on the pointer inside the function (on reverse ) :
NSInteger lastNameFirstNameSort(id person1, id person2, void *reverse)
{
NSString *name1 = [person1 valueForKey:LAST];
//...
if (*(BOOL *)reverse == YES) {
return 0 - comparison;
}
and for the id variables, they are using the variable name as is : for example here : person1
So, could someone explain me the differences between those 2 examples :
why on the first example, we don’t add a * on indexPath,
why we don’t add this * on the id variables, and we use it with *reverse in the second example?
Thanks
You are confusing dot-notation with reading a structure. This is not surprising, since Apple made them ambiguous.
indexPath.sectiondoes not mean “thesectionstructure element inindexPath. It doesn’t even mean “the propertysectioninindexPath.” It means[indexPath section]. It just calls the methodsectionand returns the result.Similarly,
foo.bar = bazdoes not literally mean “set the propertybartobaz.” It literally means[foo setBar:baz]. WhateversetBar:does will be done. In most cases, it sets an ivar.Since
indexPathis also technically a struct pointer, it is possible in some cases (but not always, and not often if you code correctly) to sayindexPath->section. You should never do this. (There are some extremely rare exceptions, but you are unlikely to encounter them.)The frustrating thing about all of this is that
foo.barmight be a structure reference or it might be a method call. Without knowing whatfoois, you can’t know. This is one of the problems with dot notation.If you find it confusing, don’t use dot notation (it continues to be a controversial feature among experienced developers). It is never required. It’s just a shortcut for the more explicit
[foo bar]and[foo setBar:baz].*(BOOL *)resultmeans “castresultfromvoid*toBOOL *and then dereference it as aBOOL. It’s unrelated to dot notation.