user1389811
user1389811

Reputation: 95

Objective C- define in C or objective C

I am a beginner so please bear with me. First of all, is all the NS stuff (NSArray, NSString, etc) objective-C specific?

Also, I'm confused about creating things in C or in objective-C. When do you use one or the other?

For example, which cases would I use the below:

NSArray *germanCars = @[@"Mercedes-Benz", @"BMW", @"Porsche", @"Opel", @"Volkswagen", @"Audi"];

or:

NSString *germanCars[] = {@"Mercedes-Benz", @"BMW", @"Porsche", @"Opel", @"Volkswagen", @"Audi"};

Thanks

Upvotes: 3

Views: 106

Answers (3)

gnasher729
gnasher729

Reputation: 52632

Your first example is an NSArray object, containing several NSString objects. Your second example is an ordinary C array, containing several NSString objects.

You will find very few methods in the Cocoa library that accept C arrays of objects. And NSArray have a huge range of useful functionality that C arrays don't have.

Upvotes: 1

Almo
Almo

Reputation: 15871

The NS stuff comes originally from the NeXTSTEP operating system: http://en.wikipedia.org/wiki/NeXTSTEP

Steve Jobs ran NeXT, and brought the stuff over to Apple when he returned there.

When working with Mac OS or iOS, it's part of the Cocoa framework. Objective-C is just the language these things are written in.

As for your coding question, use the first. You want to use the Cocoa constructs as much as possible. Cocoa is a mature, well-designed API and you will find a lot of tasks will be easier if you do things with that style.

Upvotes: 2

Ken Thomases
Ken Thomases

Reputation: 90711

The stuff prefixed with NS is specific to the Cocoa frameworks, Foundation and AppKit. They were originally designed for Objective-C, but they are accessible from other languages if they have a binding. The obvious one these days is Swift, but they can also be accessed from Python using PyObjC, etc.

In general, you should prefer the Cocoa collection classes (i.e. NSArray) over C-style types. They are higher level and thus provide better abstractions and functionality. You would use a C-style array only for APIs which require it, which are relatively rare.

Upvotes: 3

Related Questions