When I started writing code for iOS, I realized that as a C++ developer, I had to spend more time figuring out the weird things in Objective-C. This is a quick guide to help C++ experts quickly master Apple's iOS language. Please note that this is by no means a complete guide, but it saves you from having to read a 100 page manual. Besides that, I know you like my writing style. background C++ skills are required, I will compare C++ and Objective-C stuff. In addition, COM programming is also useful, because Objective-C has something similar to IUnknown, so basic COM programming is helpful (but not required) Objective C++ is a combination of C++ and Objective C. You can also use anything C++ mixed into Objective C, but remember to rename your files from .m to .mm Ding-ding! We'll get started right away. First I'll introduce the Objective-C stuff, then its C++ equivalent. Member functions
- indicates a normal member function (accessed through an object instance), while + indicates a static member function, which can be accessed without an instance. Of course, like C++, static members cannot access instance variables. Additionally, Objective-C functions can have named parameters, which makes it easier to tell which parameter gets which value. In theory, named parameters allow the programmer to pass them in any order, but Objective-C requires that they be passed in the order they are declared. Calling a member through a pointer or a static member
Objective-C uses [] to call member functions and pass in parameters separated by :, which is very friendly to the case where ptr is nil in Objective-C, in which case the "call" will be ignored (while in C++, this will throw a pointer conflict exception). This makes it possible to eliminate the check for nil objects. Protocol vs. Interface
Protocol = abstract class. The difference between Objective-C and C++ is that in Objective-C, functions do not have to be implemented. You can make an optional method passively declared, and this is just a hint to the compiler, not a compile requirement. Check if a method is implemented
Objective-C member functions are (in Smalltalk) "messages" and in Objective-C we say that the receiver (i.e. the pointer) responds to a selector, which means it implements the virtual function we are trying to call. When there is an interface, the C++ object must implement all of its member functions. In Objective-C this is not required, so we can send a "message" to something that doesn't have to implement it (and thus raises an exception). // Objective-C NSObject* ptr = ...; // some pointer if ([ptr respondsToSelector:@selector(somefunction::)] [ptr somefunction:5:3]; Now we can be sure that the receiver responds to the selector, so we can call it. In C++ there is no such check, because the implementation must always "respond to the selector", otherwise the source code will not compile at all. Note that we must know how many parameters the selector takes (hence the 2 ::s in this @selector). Downward transformation
Currently, downcasting is possible as in C++ only using NSObject's "isKindOfClass" helper, the basis for all Objective-C classes. Comply with the agreement?
Now we have to check if the receiver conforms to a protocol (or, in C++, implements an interface), so that we can send messages covered by this protocol. Hey, it's just like Java classes and interfaces, and in C++ there is no technical difference between a fully implemented class and an "interface".
id is a generic void* type for Objective-C classes. You can only use id and not void* because id can be used as a managed pointer via ARC (more on that later), and the compiler needs to distinguish between meta pointer types and Objective-C pointers. SEL is a generic type for selectors (C++ function pointers), and you create a selector by using the @selector keyword followed by the function name and a number of :::::s, depending on how many arguments are allowed. A selector is just a string that is bound to a method identifier at runtime. Class definition, methods, data, inheritance
Implementation scope in Objective-C is inside @implementation/@end tags (in C++ we can put implementation anywhere with :: scope operator). It uses @class keyword for pre-declaration. Objective-C has private protection by default, but only for data members (methods must be public). Objective-C uses self instead of this and it can also call its parent class with super keyword. Constructors and destructors
Memory allocation in Objective-C is done with the static member method alloc, which is available to all objects that are descendants of NSObject. self is assignable in Objective-C, and is set to nil if construction fails (which would throw an exception in C++). The public member function that is actually called by the constructor after memory allocation is a public member function, which is init by default in Objective-C. Objective-C uses the same reference counting method as COM, and it also uses retain and release (equivalent to IUnknown's AddRef() and Release() methods). When the reference count reaches 0, the object is removed from memory. Multithreading
Objective-C has some built-in functionality for NSObject, to operate a selector (== call a member) in another thread, in the main thread, wait for a call etc. See NSObject for more information. Memory and ARC
This is where you need to forget your good C++ habits. OK Objective-C uses a garbage collection mechanism, which we C++ people hate because it's slow and reminds us of Java. But ARC (Automatic Reference Counting) is a compile-time feature that tells the compiler "here are my objects: please help me figure out when they need to be destroyed". With ARC you don't need to send retain/release messages to your objects; the compiler does it for you automatically. To help the compiler decide how long to keep an object, you also need a weak reference to a variable. By default, all variables are strong references (== the object will live as long as the strong reference exists). You can also get a weak reference, which will lose its value for every strong reference that goes away. This is useful when class members get their values from XCode's Builder Interface (like the RC editor), and when the class is destroyed, those members will also lose their values. Strings
; NSString is an immutable representation of an Objective-C string. You can create an NSString using one of its static methods, or by prefixing a string literal with @. You can also use %@ to pass an NSString to the printf family of functions, Arrays
NSArray and NSMutableArray are two classes for dealing with arrays in Objective-C (the difference between the two is that NSArray elements must be constructed through a constructor, while NSMutableArray can be modified afterwards). For the typical constructor to work, you must pass nil as the "end element". The sorting/searching/insertion functions are the same for NSArray and NSMutableArray, in the first line of the example it returns a new NSArray, while in the case of NSMutableArray it modifies an existing object. Classification
C++ relies on inheritance to implement a known class. This is cumbersome because all user implementations must use a different type name (in this case, MyString instead of string). Objective-C allows extensions of the same type within a known class using Categories. All the source code in the link above can be viewed in the extension.h file (typically something like NSString+MyString.h). In the example above, we can immediately call the new member function without changing the NSString type to MyString. Blocks and Lambdas
Blocks are a way for Objective-C to emulate lambda functions. Check out Apple's documentation for more on blocks in the AlertView example (UIAlertView using blocks). Important tips for C++ developers using Objective-C and ARC
You already know how painful it is to give 20% discount to all customers, because your buggy software will crash in release mode, but always works fine in debug mode. No user understands programmers, right? Let's look at what's happening here. The line s = 0 assigns 0 to a variable, and therefore whatever value the variable had before is first released, so the compiler executes [s release] before the assignment. If s was already 0, assuming this is a debug build, nothing bad will happen; if s was nil, using [s release] is perfectly fine. However, in release mode, s may be a dangling pointer, so it may contain any value before it is "initialized" to 0 (dangerous, right?). In C++ this isn't a problem because ARC doesn't exist. In Objective-C the compiler has no way of knowing whether this is an "assignment" or an "initialization" (if it's the latter, it won't send the release message). Here is the correct way:
Now the compiler will not try to call a [s release] because it knows it is the first initialization of the object. Be careful! Converting from Objective-C objects to C++ types
I could analyze all this, and my advice is simple. Don’t mix ARC and non-ARC types. If you have to convert some Objective-C object, use id instead of void*. Otherwise, you will have serious memory problems. What Objective-C has that C++ doesn't Categories NSObject-based operations YES and NO (equivalent to true and false) NIL and nil (equivalent to 0) Named function parameters self (equivalent to this) which can be changed in a constructor What C++ has that Objective-C doesn't Static objects. Objects in Objective-C cannot be initialized as static or exist on the stack. Only pointers are allowed. Multiple inheritance Namespace template Operator Overloading STL and algorithms; Methods can be protected or private (in Obj-C, they can only be public) const/mutable items The friend method References Anonymous function signature (no variable name) |
<<: Sony developers' welfare Android M image released
>>: Project Soli is a more amazing interactive technology than Apple Watch
Recently, when sorting out infrared camera data i...
Recently, Kuaishou officially released the stream...
There is a lot of knowledge hidden behind the sma...
With the mature development of new energy intelli...
The Spring Festival is approaching, and young peo...
Internet promotion is to publicize and promote pr...
Recently, the WeChat official account of the Chin...
【Editor's Note】At the end of last year, OpenA...
In 2020, the offline industry was hit by the epid...
[[161600]] Have you ever thought that while we ar...
The conflicts between programmers and product man...
The operation of industrial Internet products is ...
As autumn approaches, there is always an irresist...
How much is the quotation for the development of ...