Can't find the source of this "Expected Identifier" error, any thoughts? - objective-c

I'm very new to Objective-C and programming in general and I'm having some difficulty solving a strange error I'm getting in my code. I've rechecked my code line-by-line but no matter what I do I get an "Expected Identifier" error on this one line.
NSString *text = [NSString stringWithFormat:#"Your total is $%.2f", [self.cartTotal]];
I've retyped the line several times to make sure that I wasn't missing any typos, but a little red arrow is pointing to the first closing bracket.

Take [self.cartTotal] out of the brackets. They're unnecessary here.
Should be:
NSString *text = [NSString stringWithFormat:#"Your total is $%.2f", self.cartTotal];
To help understand the error (assuming you're coming from a language like Java or C++), what you've written is the equivalent to writing this in say Java:
this.cartTotal.
Notice the hanging dot at the end? That's what you've done here basically. In Java, that dot suggests you're calling a method on whatever object cartTotal is, or access a public variable on that object. I'm not sure what a Java or C++ error message would say here, but this is the equivalent scenario.
Given #GregParker's excellent comment...
You created cartTotal by way of a #property.
#property double cartTotal; // or something like this
This creates three things:
A setter
A getter
An instance variable
The setter is accessed in two ways:
[self setCartTotal:value];
Or:
self.cartTotal = value;
These both do the same thing.
The getter is likewise accessed in two ways:
[self cartTotal];
Or:
self.cartTotal;

Related

adding Dictionary(Object) to a MutableArray Objective C

Really new to Objective C, I'm trying to add these objects to a MutableArray. My problem is this, when I'm adding new books to the array by specifying the name of the book like this:
[self.bookData addObject:[self newBookWithTitle:#"some book" andAuthor:#"some author"]];
it works. However, I want to use 2 variables I've created to get the title and author but I keep getting an error saying that it expects a ":" from the code below (inputTitle and inputAuthor are my variables that grab from the textFields
[self.bookData addObject:[self newBookWithTitle:#"%#", _inputTitle andAuthor:#"%#", inputAuthor]];
Sorry, I've looked all over but can't find out whats wrong with my syntax and where to put the : it says it needs. Any help would be appreciated.
Get rid of the #"%#", in both places of the second line. Just pass _inputTitle and inputAuthor as-is assuming they are NSString objects.
[self.bookData addObject:[self newBookWithTitle:_inputTitle andAuthor:inputAuthor]];
BTW - do yourself a favor and make your code easier to read as well as easier to debug. Split the line in two:
NSString *book = [self newBookWithTitle:_inputTitle andAuthor:inputAuthor];
[self.bookData addObject:book];
I'm assuming newBookWithTitle:andAuthor: returns an NSString. Adjust as needed.

Dot Notation vs Method Notation

I'm diving into iOS programming and I'm having difficulty getting my head around the idea of Dot Notation and Method Notation.
As far as I understand it, Dot Notation can be used to invoke setters/getters on properties and is much more cleaner to write/read. Method Notation is used to send messages to objects to manipulate them etc.
Could someone give me a simple explanation as to why the following two statements are essentially different and one will compile but the other will instead fail due to a syntax error.
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [sender currentTitle];
self.display.text = [self.display.text stringByAppendingFormat:digit];
self.display.text = self.display.text.stringByAppendingFormat:digit;
}
Thanks.
You're entering into Objective-C development at an interesting time where old syntax is being used with new syntax. Dot syntax is syntactic sugar and there are some cases where you can use it but you should not.
The following is invalid syntax. Anything where you'd use a colon (besides setters or getters), you won't use dot notation.
self.display.text = self.display.text.stringByAppendingFormat:digit;
Also, you would use stringByAppendingString, not stringByAppendingFormat
You use dot notation for accessing variables, not for calling actions that will have effects.
Correct:
self.foo.attributeOfMyClass
Incorrect:
self.foo.downloadSomethingFromAWebsite
Ensuring you always use dot notation for accessing property values and you always use bracket notation (even when you don't have to) for calling action methods, your code will be much clearer upon a glance.
Dot notation is just shorthand for a specific kind of method--namely, accessors. You may use it in the following cases:
When setting a property: foo.bar = 3; is equivalent to [foo setBar:3];.
When requesting a property: in any case except the one above, foo.bar is equivalent to [foo bar].
Dot notation is only shorthand--there is nothing magic about its relationship to properties. You could theoretically use dot notation to send any message that takes no arguments (foo.doSomething), but this would be very very bad style, as dot notation is intended for properties. Also note that if dot notation vs. square brackets is confusing you while you're learning, it's a perfectly valid choice to avoid dot notation altogether. It's just one shortcut you may use for accessors, if you like.
Actually, your second statement is not correct. Objective C way to invoke methods (messages) is using the [instance message] syntax.
As you said, the dot notation is just to call getters and setters on class properties, but not messages, that's why your second statement is not correct. The two lines you may wanted to compare are:
self.display.text = [self.display.text stringByAppendingFormat:digit];
[[self display] setText:[[[self display] text] stringByAppendingFormat:digit]];
Note that the message stringByAppendingFormat has to be called the normal way.
The dot notation is just to write faster and not so many brackets, but it will execute exactly the same instructions once compiled.
Another reason for using selector notation rather than dot notation is due to the dynamic language features in Objective C. As an example, consider the following:
NSString *s = #"Hello World!";
NSLog(#"Length is %d", s.length);
This works as we would expect. However, objects in Objective C may be passed around with type id. Consider the following:
id s = #"Hello World!";
NSLog(#"Length is %d", s.length);
This won't compile, as id doesn't have a property called length. The following will work, however:
id s = #"Hello World!";
NSLog(#"Length is %d", [s length]);
The reason this works is that Objective C knows about NSString, and so knows that there is some object type that responds to the selector length. Of course, if you try the following:
id s = [[UIView alloc] init];
NSLog(#"Length is %d", [s length]);
Your code will compile correctly, but a runtime exception will occur (unrecognized selector sent to instance) as UIView does not have a length selector.
Let's say we have the class Class with the variable variableOne we are going to use both notations.
Dot notation is the purest way to access a variable. It is also the way that bracket notation is most likely doing it behind the scenes. By typing Class.variableOne... variableOne is a part of Class and the "." after the class tells the compiler that it would like to access a part of the class--either a variable or a method.
Bracket notation is uses a method to access the variable. Let's say...
-(int) setVariable:x {
self.variableOne = x;
}
-(int) showVariable {
return self.variableOne
}
So when you're using bracket notation to set the variable [variableOne setVariable:5] or displaying the variable [variableOne showVariable] it calls the appropriate method.
This is a very simple way to think of the difference, I realize another answer has already been accepted but perhaps this answer will explain it for someone who didn't understand another answer.
When your code gets compiled, clang actually first takes all of your dot notation and turns it into method/bracket notation, so self.display and [self display] are exactly the same. Dot notation is actually fairly new as of Objective-C 2.0. It's simply for convenience.
Dot notation can only be used for properties, because doing something like you tried to do (which will not compile) gets cumbersome:
self.display.text.stringByAppendingFormat:digit;
It also wouldn't work for methods that take multiple arguments since you'd need to put spaces between arguments and suddenly the line of code would look awkward and hard to read.

What would setting a getter do?

First, some context: while answering questions on SO, I came across a post wherein the author had been trying to set a getter with syntax similar to [self.propertyGetter:newValue];. For some reason, this compiles, and I thought to myself, "this would constitute a call to nil, wouldn't it?". So, my question is, why in the heck does this 'work'? (to be perfectly clear, the poster was complaining that this had no effect, so by 'work', I mean compile).
The code you quoted is [self.propertyGetter:newValue]. Here's how the Objective-C compiler parses this.
The first thing after the left bracket has to be the receiver of the message. In that code, the receiver is the value of self.propertyGetter. The compiler transforms self.propertyGetter into [self propertyGetter]. So we can rewrite the code you quoted as [[self propertyGetter]:newValue].
Now the compiler needs to figure out the selector of the message. You usually see a keyword selector like setStatusBarHidden:animated:, which is a series of keywords followed by colons. But it turns out a keyword can be zero-length. So a colon by itself is a valid keyword selector. So the compiler sees it like this: [[self propertyGetter] :newValue]. (Using a zero-length keyword is almost always very bad style.)
You can declare an instance method using that selector. For example:
- (void):(NSObject *)newValue;
If [self propertyGetter] returns an object of a class that has that method, the code will compile and run.
If the compiler has seen any class with a method named like that, and [self propertyGetter] returns type id, then the code will compile (because id is a wildcard type and the compiler will not complain if you try to send it any known message selector). However, the app will crash at runtime if [self propertyGetter] doesn't actually understand the : message.
This compiles because all objective-C objects are dynamic entities by default. It would compile, but would crash at runtime.
Source.

NSArray (and other Cocoa types) #property values

While in the process of debugging code written by a co-worker, I stumbled across the following that has me mystified:
NSMutableArray *array = [NSMutableArray array];
NSUInteger arrayCount = array.count;
Why does this work? It also works for NSDictionary and other types, but nowhere in the documentation nor Cocoa headers can those #property definitions be found.
Googling for "NSArray property" doesn't yield many useful results, so I'm reaching out to SO for what will surely be a very embarrassing question.
It works because dot syntax has nothing to do with properties. It is simply syntactic sugar (though I don't like it, so perhaps it's "syntactic salt").
When you use dot syntax as the rvalue to an expression (or the expression to the right of the equal sign), it simple turns:
bar = myObject.thing;
Into
bar = [myObject thing];
When the dot is to the left of the equal sign (as an lvalue), it turns it into the setter. So:
myObject.thing = 42;
Becomes
[myObject setThing:42];
So yes, you can do things like myObject.retain. But you should never ever do that. You should only ever use dot syntax as accessors to declared properties (ie, things that have been explicitly declared via #property). <insert remark about how you should never use dot syntax at all.>
For more information, checkout out the documentation on dot syntax (specifically the "incorrect use" section).
the dot syntax is actually just an alternative for accessing methods that either take no parameter and return a value like array.count. It is bad form to actually access the methods in that way.
It can also be used for things like [object setValue:(id)something] and access it by doing object.setValue = something;

Should I use an intermediate temp variable when appending to an NSString?

This works -- it does compile -- but I just wanted to check if it would be considered good practice or something to be avoided?
NSString *fileName = #"image";
fileName = [fileName stringByAppendingString:#".png"];
NSLog(#"TEST : %#", fileName);
OUTPUT: TEST : image.png
Might be better written with a temporary variable:
NSString *fileName = #"image";
NSString *tempName;
tempName = [fileName stringByAppendingString:#".png"];
NSLog(#"TEST : %#", tempName);
just curious.
Internally, compilers will normally break your code up into a representation called "Single Static Assignment" where a given variable is only ever assigned one value and all statements are as simple as possible (compound elements are separated out into different lines). Your second example follows this approach.
Programmers do sometimes write like this. It is considered the clearest way of writing code since you can write all statements as basic tuples: A = B operator C. But it is normally considered too verbose for code that is "obvious", so it is an uncommon style (outside of situations where you're trying to make very cryptic code comprehensible).
Generally speaking, programmers will not be confused by your first example and it is considered acceptable where you don't need the original fileName again. However, many Obj-C programmers, encourage the following style:
NSString *fileName = [#"image" stringByAppendingString:#".png"];
NSLog(#"TEST : %#", fileName);
or even (depending on horizontal space on the line):
NSLog(#"TEST : %#", [#"image" stringByAppendingString:#".png"]);
i.e. if you only use a variable once, don't name it (just use it in place).
On a stylistic note though, if you were following the Single Static Assigment approach, you shouldn't use tempName as your variable name since it doesn't explain the role of the variable -- you'd instead use something like fileNameWithExtension. In a broader sense, I normally avoid using "temp" as a prefix since it is too easy to start naming everything "temp" (all local variables are temporary so it has little meaning).
The first line is declaring an NSString literal. It has storage that lasts the lifetime of the process, so doesn't need to be released.
The call to stringByAppendingString returns an autoreleased NSString. That should not be released either, but will last until it gets to the next autorelease pool drain.
So assigning the result of the the stringByAppendingString call back to the fileName pointer is perfectly fine in this case. In general, however, you should check what your object lifetimes are, and handle them accordingly (e.g. if fileName had been declared as a string that you own the memory to you would need to release it, so using a temp going to be necessary).
The other thing to check is if you're doing anything with fileName after this snippet - e.g. holding on to it in a instance variable - in which case your will need to retain it.
The difference is merely whether you still need the reference to the literal string or not. From the memory management POV and the object creational POV it really shouldn't matter. One thing to keep in mind though is that the second example makes it slightly easier when debugging. My preferred version would look like this:
NSString *fileName = #"image";
NSString *tempName = [fileName stringByAppendingString:#".png"];
NSLog(#"TEST : %#", tempName);
But in the end this is just a matter of preference.
I think you're right this is really down to preferred style.
Personally I like your first example, the codes not complicated and the first version is concise and easier on the eyes. Theres too much of the 'language' hiding what it's doing in the second example.
As noted memory management doesn't seem to be an issue in the examples.