need of pointer objects in objective c

旧街凉风 提交于 2021-01-21 04:26:33

问题


A very basic question .. but really very important to understand the concepts.. in c++ or c languages, we usually don't use pointer variables to store values.. i.e. values are stored simply as is in:

int a=10;

but here in ios sdk, in objective c, most of the objects which we use are initialized by denoting a pointer with them as in:

NSArray *myArray=[NSArray array];

So,the question arises in my mind ,that, what are the benefit and need of using pointer-objects (thats what we call them here, if it is not correct, please, do tell).. Also I just get confused sometimes with memory allocation fundamentals when using a pointer objects for allocation. Can I look for good explanations anywhere?


回答1:


in c++ or c languages, we usually don't use pointer variables to store values

I would take that "or C" part out. C++ programmers do frown upon the use of raw pointers, but C programmers don't. C programmers love pointers and regard them as an inevitable silver bullet solution to all problems. (No, not really, but pointers are still very frequently used in C.)

but here in ios sdk, in objective c, most of the objects which we use are initialized by denoting a pointer with them

Oh, look closer:

most of the objects

Even closer:

objects

So you are talking about Objective-C objects, amirite? (Disregard the subtlety that the C standard essentially describes all values and variables as an "object".)

It's really just Objective-C objects that are always pointers in Objective-C. Since Objective-C is a strict superset of C, all of the C idioms and programming techniques still apply when writing iOS apps (or OS X apps, or any other Objective-C based program for that matter). It's pointless, superfluous, wasteful, and as such, it is even considered an error to write something like

int *i = malloc(sizeof(int));
for (*i = 0; *i < 10; ++*i)

just because we are in Objective-C land. Primitives (or more correctly "plain old datatypes" with C++ terminology) still follow the "don't use a pointer if not needed" rule.

what are the benefit and need of using pointer-objects

So, why they are necessary:

Objective-C is an object-oriented and dynamic language. These two, strongly related properties of the language make it possible for programmers to take advantage of technologies such as polymorphism, duck-typing and dynamic binding (yes, these are hyperlinks, click them).

The way these features are implemented make it necessary that all objects be represented by a pointer to them. Let's see an example.

A common task when writing a mobile application is retrieving some data from a server. Modern web-based APIs use the JSON data exchange format for serializing data. This is a simple textual format which can be parsed (for example, using the NSJSONSerialization class) into various types of data structures and their corresponding collection classes, such as an NSArray or an NSDictionary. This means that the JSON parser class/method/function has to return something generic, something that can represent both an array and a dictionary.

So now what? We can't return a non-pointer NSArray or NSDictionary struct (Objective-C objects are really just plain old C structs under the hoods on all platforms I know Objective-C works on), because they are of different size, they have different memory layouts, etc. The compiler couldn't make sense of the code. That's why we return a pointer to a generic Objective-C object, of type id.

The C standard mandates that pointers to structs (and as such, to objects) have the same representation and alignment requirements (C99 6.2.5.27), i. e. that a pointer to any struct can be cast to a pointer to any other struct safely. Thus, this approach is correct, and we can now return any object. Using runtime introspection, it is also possible to determine the exact type (class) of the object dynamically and then use it accordingly.

And why they are convenient or better (in some aspects) than non-pointers:

Using pointers, there is no need to pass around multiple copies of the same object. Creating a lot of copies (for example, each time an object is assigned to or passed to a function) can be slow and lead to performance problems - a moderately complex object, for example, a view or a view controller, can have dozens of instance variables, thus a single instance may measure literally hundreds of bytes. If a function call that takes an object type is called thousands or millions of times in a tight loop, then re-assigning and copying it is quite painful (for the CPU anyway), and it's much easier and more straightforward to just pass in a pointer to the object (which is smaller in size and hence faster to copy over). Furthermore, Objective-C, being a reference counted language, even kind of "discourages" excessive copying anyway. Retaining and releasing is preferred over explicit copying and deallocation.

Also I just get confused sometimes with memory allocation fundamentals when using a pointer objects for allocation

Then you are most probably confused enough even without pointers. Don't blame it on the pointers, it's rather a programmer error ;-)

So here's...

  • ...the official documentation and memory management guide by Apple;
  • ...the earliest related Stack Overflow question I could find;
  • ...something you should read before trying to continue Objective-C programming #1; (i. e. learn C first)
  • ...something you should read before trying to continue Objective-C programming #2;
  • ...something you should read before trying to continue Objective-C programming #3;
  • ...and an old Stack Overflow question regarding C memory management rules, techniques and idioms;

Have fun! :-)




回答2:


Anything more complex than an int or a char or similar is usually passed as pointers even in C. In C you could of course pass around a struct of data from function to function but this is rarely seen.

Consider the following code:

struct some_struct {
    int an_int;
    char a_char[1234];
};

void function1(void)
{
    struct some_struct s;
    function2(s);
}

void function2(struct some_struct s)
{
    //do something with some_struct s
}

The some_struct data s will be put on the stack for function1. When function2 is called the data will be copied and put on the stack for use in function2. It requires the data to be on the stack twice as well as the data to be copied. This is not very efficient. Also, note that changing the values of the struct in function2 will not affect the struct in function1, they are different data in memory.

Instead consider the following code:

struct some_struct {
    int an_int;
    char a_char[1234];
};

void function1(void)
{
    struct some_struct *s = malloc(sizeof(struct some_struct));
    function2(s);
    free(s);
}

void function2(struct some_struct *s)
{
    //do something with some_struct s
}

The some_struct data will be put on the heap instead of the stack. Only a pointer to this data will be put on the stack for function1, copied in the call to function2 another pointer put on the stack for function2. This is a lot more efficient than the previous example. Also, note that any changes of the data in the struct made by function2 will now affect the struct in function1, they are the same data in memory.

This is basically the fundamentals on which higher level programming languages such as Objective-C is built and the benefits from building these languages like this.




回答3:


The benefit and need of pointer is that it behaves like a mirror. It reflects what it points to. One main place where points could be very useful is to share data between functions or methods. The local variables are not guaranteed to keep their value each time a function returns, and that they’re visible only inside their own function. But you still may want to share data between functions or methods. You can use return, but that works only for a single value. You can also use global variables, but not to store your complete data, you soon have a mess. So we need some variable that can share data between functions or methods. There comes pointers to our remedy. You can just create the data and just pass around the memory address (the unique ID) pointing to that data. Using this pointer the data could be accessed and altered in any function or method. In terms of writing modular code, that’s the most important purpose of a pointer— to share data in many different places in a program.




回答4:


The main difference between C and Objective-C in this regard is that arrays in Objective-C are commonly implemented as objects. (Arrays are always implemented as objects in Java, BTW, and C++ has several common classes resembling NSArray.)

Anyone who has considered the issue carefully understands that "bare" C-like arrays are problematic -- awkward to deal with and very frequently the source of errors and confusion. ("An array 'decays' to a pointer" -- what is that supposed to mean, anyway, other than to admit in a backhanded way "Yes, it's confusing"??)

Allocation in Objective-C is a bit confusing in large part because it's in transition. The old manual reference count scheme could be easily understood (if not so easily dealt with in implementations), but ARC, while simpler to deal with, is far harder to truly understand, and understanding both simultaneously is even harder. But both are easier to deal with than C, where "zombie pointers" are almost a given, due to the lack of reference counting. (C may seem simpler, but only because you don't do things as complex as those you'd do with Objective-C, due to the difficulty controlling it all.)




回答5:


You use a pointer always when referring to something on the heap and sometimes, but usually not when referring to something on the stack.

Since Objective-C objects are always allocated on the heap (with the exception of Blocks, but that is orthogonal to this discussion), you always use pointers to Objective-C objects. Both the id and Class types are really pointers.

Where you don't use pointers are for certain primitive types and simple structures. NSPoint, NSRange, int, NSUInteger, etc... are all typically accessed via the stack and typically you do not use pointers.



来源:https://stackoverflow.com/questions/17992127/need-of-pointer-objects-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!