This question already has answers here:
Objective-C dot notation with class methods?
(3 answers)
Closed 9 years ago.
This question related to knowing something we don't know. I'm researching with "Why people don't use this"? Is any reason behind this related to specific tech? So read it carefully and give downvote or give correct answer.
We can write
NSMutableString *string = NSMutableString.string;
instead of
NSMutableString *string = [NSMutableString string];
Same as how can we write this method,
NSMutableString *string = [NSMutableString stringWithString:#"test"];
Update:
This question is not an duplicate which is little bit different. And I accept with below answers which is not recommended for good programmers. But They didn't explain Why, for What reason, programmers should avoid this? Could anyone give clear explanation about this with proper link or document?
NSMutableString.string is a hack. It "works" for the same reason that myString.length and [myString length] produce the same result. However, since dot notation is not used with an actual property, it is an abuse of the language feature, because properties have a different semantic. For example, when you access a property multiple times, you naturally expect to get the same result, unless the state of the object has changed in between the two invocations. Since NSMutableString.string produces a new string object on each invocation, it breaks the semantic expected of the "proper" properties, bringing down the readability of your program.
Objective-C does not have a general way of calling a method with arguments using the dot notation. There feature is very specific to properties. Although theoretically you could use MyClass.xyz = abc in place of [MyClass setXyz:abc], but that would be a hack as well.
To answer your question, Objective-C does not offer a way to call [NSMutableString stringWithString:#"test"] with dot notation.
It's just a syntactic sugar. string method has no arguments so it's treated like a getter, which is not in fact. stringWithString: is method with parameter, so you can't call like that.
In general, I'd not recommend using dot syntax with methods, it's confusing.
Objective-C dot notation with class methods?
Update
I don't think there is any technical reason you should avoid it.
It's rather in means of coding style, keeping code clean and consistent.
Related
Recently in a iOS project I have refactored money data type from double to NSDecimalNumber to get a rid of discrepancies caused by handling money with doubles.
The refactoring is complete but my concerns are for all those comparisons made through standard operators that are not raised as errors by the compiler because comparing objects is still valid (memory addresses are compared) but not logically correct
double a = 4;
double b = 3;
if(a > b) do stuff //valid and logically correct
NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithString:#"4"];
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithString:#"3"];
if(a > b) do stuff //valid but not logically correct as here the memory addresses of variables will be compared instead of values.
Is there any way to make the compiler highlight these situations?
My first idea was to create a category for NSDecimalNumber and overloading operators so that they would work properly for them and, as it s not possible to override operators in Obj-C, I tried 2 different ways to accomplish this:
Creating a swift extension of NSDecimalNumber where I overload those operators (in swift it s possible to override standard operators) and then using those new methods in my Obj-c environment through Swift bridge. After some tests and have red a lot on StackOverflow it seems this approach is not possible as Obj-C will always treat standard operators in the common way (comparing addressed for objects)
Creating a category for NSDecimalNumber where I overload those operators though C++ that gives the option to overload operators to the programmer. The problem here is that I am not confident with C++ and I cannot find any example to address me.
So in the end I need a way to highlight any comparison between objects made with standard operators.
Any help is really appreciated,
Thanks.
I'm just going through Apple's iOS development tutorial at the moment and reading the chapter on the Foundation framework and value objects.
Just on the NSNumber class, it says:
You can even use NSNumber literals to create encapsulated Boolean and
character values.
NSNumber *myBoolValue = #YES; NSNumber *myCharValue = #'V';
I'm just wondering, when, or why, or in what scenario, might you want to use NSNumber for a character value rather than using NSString, say?
An NSNumber is useful for encapsulating primitive values to be inserted into Objective-C collection classes such as NSArray, NSSet, NSDictionary, etc.
Image a scenario where you would want to iterate over each character in an ASCII string and extract a unique set of vowels used. You can evaluate each character and add it to an NSMutableSet. To do so, you would need to encapsulate each character in an NSNumber as NSMutableSet expects an Objective-C object. This is just one example, but the concept applies to many situations where primitives need to be added into a collection.
Well, one case is where you're using KVC to set a value for a key, and the property type is char:
[object setValue:#'a' forKey:someCharPropertyName];
You can use NSNumber with characters to return its ASCII Code, so V would return 86.
I don't think many people use it that much, but you could probably use it for character validation. I think it just one of those things where Apple went, yeah, lets put that in for the heck of it.
It's really not used for much else. The #YES and #NO is the same as YES and NO, so its kinda inelegant in some places.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm struggling with what I imagine is fairly simple - but I need to create a string by joining various strings and string vars together - this is what i have so far -
_msgTxt = #"I have achieved great results with my instructor%#", _usrName, #"Check her out here", _usrURL;
any tips on where i'm going wrong? I'm hoping to achieve a long string ie ' I have achieved great results with my instructor Zoe Edwards. Check her out here http://www.nme.com" which could be posted to social media channels.
Cheers
You'll need to use stringWithFormat.
Example:
_msgTxt = [NSString stringWithFormat:#"I have achieved great results with my instructor %#. Check her out here %#", _usrName, _usrURL];
One thing to keep in mind using the example above is that the objects/variables provided should appropriately use the description method to output user visible strings. NSString does, but other objects may output something which isn't user friendly.
If this is the case, you should use an NSString object within the parent object to display the information (You'd need to create this yourself; _usrURL.userFriendlyString for example).
Use [NSString stringWithFormat:*enter you stuff here*];
While stringWithFormat: will work as proposed by the other answers, it isn't very efficient if you just want to concatenate a number of strings in a set order. The power of stringWithFormat: comes from the contents of the format and the ability to reorganise and 'format' contents with the parameter specifiers. But it comes with a cost because the format string has to be parsed and processed.
For simple string concatenation, use NSMutableString and the appendString: method. (and note that you can also use appendFormat: of you have one part that needs it...).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there some literal dictionary or array syntax in Objective-C?
I have recently noticed that something strange seems to work in objective-c.
When I have an array,
NSArray *myArray = #[#"1", #"b", #"3", #"d"];
I can normally access the second element by,
NSString *element = [myArray objectAtIndex:1]; // second element
however I seem to now also be able to access it via.
NSString *element = myArray[1];
Does anyone know if this is now a defined behaviour and therefore safe to use, or should I avoid it? Thanks to anyone who can help!!
This syntax was added in Clang 3.3 : Objective C Literals. Essentially, the compiler converts expressions of the type objCObj[idx] to the expression [objCObj objectAtIndexedSubscript:idx]. It also works for dictionaries, and you're free to adopt it for your own objects.
As such, you're perfectly safe using it, assuming you'll be using a modern version of Objective C and suitably updated Objective C compiler (i.e. Clang).
this is a new feature of objective-c and avaiable since xCode 4.5
its safe to use this syntax, you can even give your own classes support for this.
Ya, it's safe to use these syntax.
Those syntax are part of Modern Objective-C.
You can check this article for more options: ObjectiveCLiterals
It's a perfectly valid code for the latest version of the LLVM compiler.
So far, it's invalid for other compilers (e.g. GCC).
Whether you should avoid it or not - well, it's a matter of taste. There are several big discussions about it on the internet since the indexing behaves slightly different (a whole different method is used to implement it).
There are also discussions whether to use the expression literals or not since there are ocassions when they are making the code less readable (e.g. they are written like literals but they actually are autoreleased objects). Note that everything is done using literals can be done using simple macros.
I'm working in a ruby app in which symbols are used in various places where one would usually use strings or enums in other languages (to specify configurations mostly).
So my question is, why should I not add a to_str method to symbol?
It seems seems sensible, as it allows implicit conversion between symbol and string. So I can do stuff like this without having to worry about calling :symbol.to_s:
File.join(:something, "something_else") # => "something/something_else"
The negative is the same as the positive, it implicitly converts symbols to strings, which can be REALLY confusing if it causes an obscure bug, but given how symbols are generally used, I'm not sure if this is a valid concern.
Any thoughts?
when an object does respond_to? :to_str, you expect him to really act like a String. This means it should implement all of String's methods, so you could potentially break some code relying on this.
to_s means that you get a string representation of your object, that's why so many objects implement it - but the string you get is far from being 'semantically' equivalent to your object ( an_hash.to_s is far from being a Hash ). :symbol.to_str's absence reflects this : a symbol is NOT and MUST NOT be confused with a string in Ruby, because they serve totally different purposes.
You wouldn't think about adding to_str to an Int, right ? Yet an Int has a lot of common with a symbol : each one of them is unique. When you have a symbol, you expect it to be unique and immutable as well.
You don't have to implicitly convert it right? Because doing something like this will automatically coerce it to a string.
"#{:something}/something_else" # "something/something_else"
The negative is what you say--at one point, anyway, some core Ruby had different behavior based on symbol/string. I don't know if that's still the case. The threat alone makes me a little twitchy, but I don't have a solid technical reason at this point. I guess the thought of making a symbol more string-like just makes me nervous.