Bracket syntax in Objective-C [duplicate] - objective-c

This question already has answers here:
What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?
(4 answers)
Closed 9 years ago.
I like to mess with coding every now and then as a hobby and I noticed an unfamiliar syntax in some of the Apple Developer documentation:
newSectionsArray[index]
I normally expect something like:
[object method]
Can anyone explain this to me?
Thanks!

It's called object subscripting, as explained here
Its syntactic sugar, as
newSectionsArray[index]
gets translated by the compiler to
[newSectionsArray objectAtIndexedSubscript:index];
NSDictionary implements subscripting too, so you can access an element in this fashion:
dictionary[#"key"]
The cool (and potentially dangerous) feature is that this is generalized, so you can even have it on your own classes.
You just need to implement a couple of methods
(for indexed access)
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
or (for keyed access)
- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)obj forKeyedSubscript:(id)idx;
and you they will be called whenever you use bracket notation on the instances of you custom class.
So you could end up coding a grid-based game and accessing the elements on the grid by
board[#"B42"]; // => [board objectForKeyedSubscript:#"B42"]
or moving a piece on the board by
board[#"C42"] = #"Troll"; => [board setObject:#"Troll" forKeyedSubscript:#"C42"];
Nice, but I wouldn't abuse of it.

That's literal syntax, introduced in Clang 3.4. You could however use the old syntax [newSectionsArray objectAtIndex:index]. it's the same thing.

newSectionsArray is probably an array (i.e. a contigous block of multiple objects of the same type) and index an integer. newSectionsArray[index] gives you the object at position index (starting counting with 0).

Related

Create Objective-C literal object like NSString [duplicate]

This question already has answers here:
Can the new Clang Objective-C literals be redirected to custom classes?
(2 answers)
Closed 6 years ago.
I want to know if it's possible to create Objective-C literals like NSString, where instead of [[Object alloc] init], and then assigning you can just assign a value to it, such as #"A string".
Obviously NSString is an object because it has methods to manipulate the data in addition, so in theory there should be a way to do it yourself, but I'm not sure where to even go about finding stuff like this.
Objective-C is C. The primitive (what I would call scalar) data types are all numbers and are completely defined by the language; you cannot add to them (though you can rename them using typedef. The corresponding literals, such as 1 and "hello", are also part of C.
Similarly, literals like #"howdy" and #[#"howdy"], though defined by Objective-C rather than C, are part of the language and you cannot change or add to them, as the literal syntax is built into the language.

Why do objective-c array parameters not use colon notation?

Im currently learning some objective-c from the big ranch guide book. My understanding is that methods with multiple parameters use colons to separate each parameter, but when reading about creating arrays, i found this snippet of code:
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday, nil];
This has left me confused as i thought objective-c method parameters must each be preceded by a portion of the method name along with a colon. Can anybody explain this to me?
This is an exception to the rule; this is commonly called a variadic method. If you look at the definition in NSArray.h:
+ (instancetype)arrayWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
you see that you can specify an arbitrary number of parameters, as long as the last one is nil (this is called the sentinel).
This saves the developers from creating a large number of different methods having roughly the same functionality, each of which accept a different number of parameters. They did so in NSObject, where you have
- (id)performSelector:(SEL)aSelector withObject:(id)object1;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
(but no further methods).
The method only has one parameter, a variable parameter list.
Here is the Objective-C declaration from the Apple Developer website:
+ (instancetype nonnull)arrayWithObjects:(ObjectType nonnull)firstObj, ...;
There's no need for colon separation, because the object list is treated as one parameter, even thought it looks like many parameters!

How can I get sizeof class based on NSObject [duplicate]

This question already has answers here:
Checking the size of an object in Objective-C
(6 answers)
Closed 8 years ago.
I'm new to obj-c . During these day's practices I noticed that every class based on NSObject can't have an entity like : NSObject en; in c++ but NSObject* en instead.
But, sometimes I need to know the Size of an Object.I can't simply write sizeof(en) because en is a pointer var.I can't simply use sizeof(NSObject) neither for the compiler telling me Application of sizeof to interface 'XXXX' is not supported on this architecture and platform.
I want to know if there is a way to get sizeof(NSObject) .If not,what the syntax is designed this for & any other ways to get the size.
From doc
class_getInstanceSize
Returns the size of instances of a class.
size_t class_getInstanceSize(Class cls)
Parameters cls A class object.
Return Value The size in bytes of instances of the class cls, or 0 if
cls is Nil.
But I doubt this is what you really want. Because I never found it useful and can't think a case it may be useful. (other than learning memory layout of objects and low level implementation details)
First, you should import malloc.h
If you use Non-ARC:
malloc_size(myObject);
if you are using ARC:
malloc_size((__bridge const void *) myObject));
This linker is a question similar to yours.

Mutable array object types [duplicate]

This question already has answers here:
NSMutableArray - force the array to hold specific object type only
(12 answers)
Closed 9 years ago.
I'm programming on Objective C for the first time, coming from C++ (so far I like
the latter much better!). I have a question regarding mutable arrays, namely I want to create one with the specific type of one of my objects, 'CMParticle', instead of the generic ID type. To access data in my object from my mutable array, I have to cast it as one of my objects each time (which is I believe cumbersome) like so:
rij[0] = ((CMParticle *)particles[*pi]).crds[0] - ((CMParticle *)particles[*pj]).crds[0];
where 'particles' is my mutable array of CMParticle objects. I would rather do this
rij[0] = particles[*pi].crds[0] - particles[*pj].crds[0];
Prior to this I declare my mutable array like so:
particles = [NSMutableArray array];
It would be nice if I could declare this array with my type somehow so I don't have to typecast every time. Is there a way to do this?
What you're trying to do doesn't actually make sense in Objective C.
C++ containers are homogenous, but generic. You can have a vector<CMParticle>, or a vector<int>, and they're different types.
ObjC containers are heterogeneous. You just have an NSArray, and it can hold CMParticle objects, NSNumber objects, or anything else, all mixed up in one big array.
You generally don't need these casts at all. If you want to send a message to my_array[3], just do [my_array[3] doSomething:15]. Just like a higher-level language (Python, Ruby, Smalltalk, Javascript, etc.).
The only problem is that (unlike Python, etc.), there are a few cases where you do need the cast. Most critically (and annoyingly), if you want to access members directly, you have to cast first. This is one of the reasons that ObjC (unlike Python, etc.) encourages you to use #property and/or explicit accessors instead of directly accessing members. (Also, as a more minor annoyance, because variables have declared types, you can't just write tempval = my_array[3];, you have to specify the type, like: CMParticle *tempval = my_array[3].)
Another way to look at this: C++ extends C's static, weak type system to give you a stronger static type system; ObjC instead bolts on a separate dynamic type system (unfortunately leaving the existing C stuff unchanged, which is where the occasional problems come in).
You can pretty easily write your own NSMutableArray subclass that's generic (taking the class at runtime, unlike C++'s compile time, of course) and homogenous, but all that does is add restrictions; the elements will still be id everywhere. The only way around that is to write a custom class for each array: MutableCMParticleArray, MutableNSNumberArray, etc.

What does `->` symbol represent in objective-c [duplicate]

This question already has answers here:
What does this ' ->' mean in c/objective-c?
(7 answers)
What is the difference between '->' (arrow operator) and '.' (dot operator) in Objective-C?
(3 answers)
Dot (".") operator and arrow ("->") operator use in C vs. Objective-C
(5 answers)
Closed 10 years ago.
I have been looking at some code and come across the symbol -> being used like obj->method(argument); I have done a little bit of research and found it basically is the same as [obj method:argument]; but I am unsure what -> actually is or does.
So my question is, what does the -> symbol mean in objective-c?
It means the same as the struct dereference operator does in C, which is used to access fields within the struct via a pointer:
struct mystruct
{
int field;
};
struct mystruct *mystruct = ...;
printf("field=%d\n", mystruct->field);
In Objective-C it can also be used to access fields within Objective-C objects:
#interface MyObj : NSObject
{
#public
int field;
}
#end
MyObj *myObj = [[MyObj alloc] init];
NSLog(#"field=%d", myObj->field);
Note that you can only access these fields externally if they are declared #public.
I have been looking at some code and come across the symbol -> being
used like obj->method(argument); I have done a little bit of research
and found it basically is the same as [obj method:argument]; but I am
unsure what -> actually is or does.
So my question is, what does the -> symbol mean in objective-c?
Exactly the same thing it means in C; it is for accessing an item in a C structure. Way back in the days of yore, Objective-C was implemented purely as a C preprocessor extension + a runtime. Classes were nothing more than concatenated C structures and the preprocessor turned each ivar access into self->ivar.
I.e. ivar and self->ivar do the same thing (in a method of class).
Now, you can use -> to poke at some other object's (#public) ivars. But don't. That breaks encapsulation exactly because Objective-C's line of encapsulation is drawn at the method interface. Always use the setters/getters such that behavior can be either observed or overridden.
Finally, no, there is nothing like obj->method(argument) anymore. There was, once, in a failed experiment called Modern Syntax, but it was abandoned because it was a pointless waste of time. You can't use -> to invoke methods.