Difference between CFMutableArray and NSMutableArray? - iphone

What is the difference between NSMutableArray and CFMutableArray?
In which case(s) should we use one or the other?

CFMutableArray and NSMutableArray are the C- and Objective-C-equivalents of the same type. They are considered a "toll free bridged" type pair, which means you can cast a CFMutableArrayRef to a NSMutableArray* (and vice versa) and everything will just work. The cases in which you would use one over the other is ease-of-use (are you using C or Objective-C?) or compatibility with an API you would like to use. See more information here.

At runtime, they are identical. They are the same, they are toll-free bridged types - you can safely (and efficiently) cast one to the other.
They are different types, available in different/overlapping languages.
CFMutableArrayRef is the opaque C object interface
NSMutableArray * is the Objective-C interface
They may be freely interchanged, and the difference is the declaration that says one is a pointer to an opaque type, vs a objc object.
Also, you can (sorta - it requires a little more implementation than usual) subclass NSMutableArray type using objc.

OSX's APIs are layered, there are basic low-level APIs that are self-cotnained and then there are richer APIs built on top of them, in turn using the lower level APIs themselves.
CFMutableArray is part of the CoreFoundation framework and used by the lower-level APIs. NSMutableArray (I guess NS stands for NextStep) is part of the Foundation framework and used in higher level APIs like the AppKit or Cocoa.
Which you should use depends on where you are working. If you're working in a rich user interface using Cocoa, NSMutableArray is the right choice. If you're working on a daemon, driver or anything else just using CoreFoundation, use CFMutableArray.
Luckily, as pointed out above, many of these CF/NS types are toll-free bridged and so you can use CoreFoundation APIs from e.g. Cocoa without having to constantly convert types.

Related

Swift foundation vs standard library?

Question
- What is the difference between Swift Foundation and standard library?
I know they are not in the same repository. Swift standard library and Swift Foundation.
My understanding is that Swift standard library is low level library that are support for core data types, array, etc... written in swift. And Swift Foundation is for higher level which are already included common utilities codes written in swift language. But my confusion is that why are the objective-c classes like NSArray are included in Foundation library? Can you explain me with more details?
To understand what's going on here, first distinguish three things:
Swift library is the Swift native types, like String and Array.
Foundation is the Cocoa Objective-C basic set of types, like NSString and NSArray and NSDate and NSData.
Swift also contains an overlay library that shadows (without obscuring) types in the Foundation. For example, Date shadows NSDate, and Data shadows NSData. This makes the Cocoa Foundation a lot easier to use in Swift.
Note that there are two very different relations in which a Swift type can stand with respect to a Cocoa Objective-C type.
String and Array are completely independent native Swift types. They are bridged to NSString and NSArray respectively, but they exist without Foundation.
Data and Date are merely facades for NSData and NSDate respectively. If you import Swift but not Foundation, Data and Date are not even present.
Okay, so far so good. But this situation presents a quandary, because one would like to use Data and Date without the need for Foundation, in places like Linux that do not have it in the first place. Therefore, the project you have pointed to, https://github.com/apple/swift-corelibs-foundation, provides a backing for Data and Date (and so on) independent of Foundation.
But if you are developing for iOS or MacOS you would never use it, because the real Foundation is present.
Swift Standard Library
NeXTSTEP -> Cocoa -> Swift Standard Library
[Cocoa]
Swift Standard Library:
describes fundamental data types, protocols, functions... their definitions and algorithms to work with
implementation - swift/stdlib/public/
Standard library core - swift/stdlib/public/core/ - data structures and algorithms
Runtime(Swift Run Time Library) - swift/stdlib/public/runtime/ - low level stuff which written on more low level language(C++, Objective-C) which is a layer between compiler and Standard library core. It responsible for dynamism(runtime features) - memory management, reflection...
SDK Overlays - which helps to support compatibility with Swift with Objective-C
Swift Foundation - swift/stdlib/public/Darwin/Foundation/ -> swift-corelibs-foundation is a part of SDK Overlays which allows you to work with Objective-C Foundation framework from Swift codebase.
[Binary representation]

Key Value Coding Use in Swift

I want to know the use of KVO in swift as I read in Apple Doc or any other online articles it states that it provides indirect access to properties and addressable via string. I have a set of doubts.
If I can set the property directly via person.name = "John" they why to use a Set Value for key name = "John" indirectly
Apple doc says key-value coding compliant can participate in a wide range of Cocoa technologies like Core Data. Why it's used and not in other frameworks
It is used during runtime or dynamic to set value. How it is?
Is it TypeSafe and how?
Its an Objective - C feature then why still used in Swift 4 with latest improvements with ./Type.property access and set
If I can set the property directly via person.name = "John" they why
to use a Set Value for key name = "John" indirectly
Please read “What is the point of key-value coding?”
Apple doc says
key-value coding compliant can participate in a wide range of Cocoa
technologies like Core Data. Why it's used and not in other frameworks
It's used where appropriate. It's used where it is helpful and the performance is acceptable. If it's not useful, or if its performance is too low, it's not used.
It is used during runtime or dynamic to set value. How it is?
Key-Value Coding uses the Objective-C runtime to look up getter and setter methods, and to find the types and locations of instance variables if the setters don't exist. See Friday Q&A 2013-02-08: Let's Build Key-Value Coding for a detailed analysis.
Apple documentation briefly describes the implementation of Key-Value Observing here. It's short enough to quote entirely:
Automatic key-value observing is implemented using a technique called
isa-swizzling.
The isa pointer, as the name suggests, points to the object's class
which maintains a dispatch table. This dispatch table essentially
contains pointers to the methods the class implements, among other
data.
When an observer is registered for an attribute of an object the isa
pointer of the observed object is modified, pointing to an
intermediate class rather than at the true class. As a result the
value of the isa pointer does not necessarily reflect the actual class
of the instance.
You should never rely on the isa pointer to determine class
membership. Instead, you should use the class method to determine the
class of an object instance.
Mike Ash gave a more detailed analysis in Friday Q&A 2009-01-23.
Is it
TypeSafe and how?
It's not particularly type safe. For example, it doesn't stop you from storing a UIView in a property that's declared as NSString, or vice versa.
Its an Objective - C feature then why still used in
Swift 4 with latest improvements with ./Type.property access and set
It's still used because most of Apple's SDK is still implemented in Objective-C, and because it lets you do things that you cannot do in Swift without much more “boilerplate” (manual, repetitive functions). The trade-off is that Objective-C is lower performance. In many, many cases, the lower performance of Objective-C (compared to Swift) is not a significant problem, and the increased dynamism is very helpful.

benefits of using CF variables over NS ones

I noticed that there are variables and functions used by many libraries that start with CF and ends with Ref, like: CFStringRef , CFURLRef , CFHTTPMessageCreateRequest , etc ...
1) what does CF stand for ? I don't know why apple does not say a word about such abbreviations.
2) what's the benefit(s) of using (for ex.) CFStringRef instead of using NSString ?
3) if it's better to use these CF variables, should I then replace all regular variable like NSString with CFStringRef ?
CF stands for Core Foundation. If you're interested in learning more about that, you can start by reading the Core Foundation Design Concepts Guide. There are also the String Programming Guide for Core Foundation and Collections Programming Topics for Core Foundation, which will tell you more about CFStringRef and the various collection types (arrays, dictionaries, and so forth).
Basically, Core Foundation is a relatively low-level framework that does some of the same things that Foundation does, but is written in C, and not Objective-C. Some Core Foundation "classes" (they're not really classes) are also "toll-free bridged" with their Objective-C counterparts, for example, it is possible to cast a CFStringRef to an NSString * (though it is a little more complicated with ARC).
If you don't need specific APIs that are only available in Core Foundation, there's absolutely no need to use it instead of Foundation. Core Foundation code tends to be less readable than Objective-C and also makes memory management a bit more complicated.
However, it can be quite useful to familiarize oneself with the basic concepts of Core Foundation, because there are still quite a few other frameworks that are built similarly. Core Text and Core Graphics are examples – while they don't formally belong to Core Foundation, they use the same naming and memory management conventions. There are also some APIs that are only available in Core Foundation and don't have Foundation counterparts – CFBagRef or CFBitVector (both collection types) would be examples.
From the Apple documentation:
Core Foundation is a library with a set of programming interfaces conceptually derived from the Objective-C-based Foundation framework but implemented in the C language. To do this, Core Foundation implements a limited object model in C. Core Foundation defines opaque types that encapsulate data and functions, hereafter referred to as “objects.”
This is essentially sums up the difference. Core Foundation (CF) provides pure C implementations of many of the Objective-C implementations that come with the language in the form of the Foundation framework. It is correct that NS stands for 'NeXTSTEP', the name of the operating system that formed the absis for much of Mac OS X, but it also indicates that a type is an Objective C class. CF types are pure C implementations and come with C functions to manipulate them.
There are occasionally times that using the CF structures brings an advantage over the NS equivalent. For example, CFDictionary places fewer restrictions on values and keys than does NSDictionary. But unless any such problem comes up there isn't a reason for you to change your references to their CF equivalents. ARC will also not work as easily with CF types.
It is also possible to map between CF and Foundation using toll-free bridging.
Objective-C is built on the c language, the CF (Core Foundation) types are C structs, and are usually wrapped in an Objective-C object (CFStringRef is wrapped by NSString, CGImageRef is wrapped by UIImage etc)
Unless you have a good reason, use the Objective-C level code. The memory management is much simpler (automatic for ARC), and in general your code will be much cleaner
Edit: as #omz pointed out, wrapped is incorrect for NSString, it is bridged, some of the other answers explain this concept

Core Data primitive accessor methods valid for iPhone?

I'm getting mixed signals as to whether primitive accessor methods (of the form setPrimitive*YourAttribute* vs setPrimitiveValue:*value* forKey:#"*YourAttribute*" in Core Data objects are meant for use with iPhone code or just Mac. On the one hand, the Apple documentation doesn't seem to mention them as available for iOS, just Mac OS X v10.5. On the other hand, they work with my iPhone app's code, albeit with compiler warnings, e.g. "Method xxxx not found (return type defaults to 'id')".
Can someone confirm one way or another?
In the Overview of the Managed Object Accessor Methods section of Core Data Programming Guide it states that primitive accessors are automatically generated for you, but you will need to declare the properties to suppress compiler warnings. You say using primitive accessors works in your code (even with the warnings) so it seems like it's supported in iOS.
It appears that Apple's documentation pages aren't always rigorous in mentioning a given feature's availability in the various OSes.
You could use NSNumber instead. For bools you would have and [NSNumber numberWithInt:0] for NO and [NSNumber numberWithInt:1] for YES for example. Same logic with integers, doubles, float. It's much easier this way. Your property would be like: NSNumber *myInteger , you would only have to box and unbox it when you retrieve or store it. That's how I would do it.

Using Structs in Objective-C (for iOS): Premature Optimization?

I realize that what counts as premature optimization has a subjective component, but this is an empirical or best-practices question.
When programming for iOS, should I prefer using struct and typedefs where the object has no "behavior" (methods, basically)? My feeling is that the struct syntax is a bit strange for a non-C person, but that it should be WAY lower profile. Then again, testing some cases with 50K NSObject instances, it doesn't seem bad (relative, I know). Should I "get used to it" (use structs where possible) or are NSObject instances okay, unless I have performance problems?
The typical case would be a class with two int member variables. I've read that using a struct to hold two NSString instances (or any NSObject subclass) is a bad idea.
Structs with NSObject instances in them are definitely a bad idea. You need -init and -dealloc to handle the retain count correctly. Writing retain and releases from the caller side is just insane. It will never pay off.
Structs with two int or four doubles are borderline cases. The Cocoa framework itself implements NSRect, NSPoint etc. as a struct. But that fact has confused lots and lots of newcomers. Honestly, even the distinction between primitive types and object types confused them. It becomes even confusing to me when you have structs as properties of an object: you can't do
object.frame.origin.x=10;
If you start making your own structs, you need to remember which is which. That's again a hassle. I think the reason why they (NSRect etc.) are structs are basically historical.
I would prefer to make everything objects. And use garbage collection if available.
And, don't ask people if something is worth optimizing or not. Measure it yourself by Instruments or whatever. Depending on the environment (ppc vs intel, OS X vs iOS, iPad vs iPhone) one way which was faster in a previous system might be slower in a new system.
An Objective C object has almost the same storage as a struct, except it is 4 bytes (8 bytes on 64 bit) bigger. That's it - just one pointer into a place where the runtime holds all the class information.
If you are that tight on memory, then lose the 4 bytes, but usually that's only for large numbers of objects: 50,000 Nsobjects vs structs is only 200k - you get a lot of stuff for that 200k. For a million objects, the cost will add up on an iPhone.
If you want to say transfer the items to openGL or need a c array for other purposes, then another option is to make ONE NSObject that has a malloc'ed pointer to all 50,000 integers. Then the objective c memory overhead is ~0, and you can encapsulate all the nasty malloc and free() stuff into the innards of one .m file.
Go with regular objects until you hit a measurable performance bottleneck. I’ve used high-level code even in tight game loops without problems – messaging, collection classes, autorelease pools, no problems.
I see no problem at all with using structs to hold small quantities of primitive (i.e. non object) types where there is no behaviour required. There are already several examples of this in the Cocoa frameworks (CGRect, CGSize, CGPoint, NSRange for example).
Do not use structs to hold Objective-C objects. It complicates the memory management in the reference counted environment and may break it altogether in the GC environment.
For me, I would prefer to use regular objects because you can easily do Object job with it like retain, release, autorelease. I only see quite few structs in Cocoa Framework like CGSize, CGRect and CGPoint. I think the reason is that they are being used a lot
I believe is a good idea to use structs specially if you are dealing with C-based frameworks , lets says OpenGL, CoreGraphics, CoreText specially stuff that will require a couple/triple of ints, doubles, chars, etc. (If they are already not implemented in some of Apple Frameworks: CGRect, CGPoint, CTRect, NSRange, etc...) C stuff plays and looks better with other C stuff.
I don't think I would write a subclass of NSObject containing a couple of ints. It's almost ridiculous. lol.