I need a good analogy to understand class methods and instance methods

I'm quite confused as reading a book is read in the NSNumber class and talks about all the different methods you can name. I have a couple of questions:

1.) You do not need to call typical alloc or init classes in foundation classes?

2.) In what cases would you use, say, the number WhithChar: as opposed to initWithChar (I think that the part that amazes me the most is not quite sure that I will adhere to this concept at the level that I need, if you guys can break me down for me, I think it really will help me overcome this humor row.

Thanks,

Nick

+3
source share
3 answers

Class / instance attributes

Classes are similar to house type drawings. Instances are like real houses. Thus, you can only have one project for one type of house, but you can have several real houses of the same type. In addition, you can have several drawings, and each drawing describes a different type of house.

Another analogy you can use is that classes are like cookie cutters, and instances are like cookies made from a cookie cutter.

How does this relate to Objective-C

There is one “class object” for each class of your code. To refer to a class object, you simply use the class name. - a class method that allocates a new instance as follows: alloc

MyWidget* w = [MyWidget alloc];

alloc , - . init - , . , , :

MyWidget* w = [[MyWidget alloc] init];

:

MyWidget* w = [MyWidget alloc]; //alloc is being called on the class
w = [w init]; //init is being called on the instance

factory, numberWithChar:. , numberWithChar: :

+(NSNumber*) numberWithChar:(char)c;
{
    return [[[NSNumber alloc] initWithChar:c] autorelease];
}

, numberWithChar: .

. .

+3

1) alloc init . numberWithChar - , , alloc, init autorelease .

2) numberWithChar , , ( - NSArray, retain), . initWithChar retain -ed, , , .

, , init - alloc, , .

?

EDIT:

, , , , , NSString, NSStrings, NSString. , 100% . alloc - , stringWithFormat - ..

, , .

+3

, : Objective-C , . .

factory. , factory.

+1

Source: https://habr.com/ru/post/1727842/


All Articles