0

クラスメソッドを作成する必要がある場合、理解するのが難しいと感じています。私が読んだことから、それらは新しいオブジェクトを作成するために重要ですが、その方法はわかりません。次のクラスは、単純な形状の黒い長方形を作成します。インスタンスメソッドではできないことを行うためにクラスメソッドを組み込む方法を誰かに教えてもらえますか?

Shape.h

#import <UIKit/UIKit.h>
@interface Shape : UIView; 
- (id) initWithX: (int)xVal andY: (int)yVal;
@end

Shape.m

#import "Shape.h"
@implementation Shape 
- (id) initWithX:(int )xVal andY:(int)yVal {
self = [super init];    
UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(xVal, yVal, 10, 10)];
shape.backgroundColor = [UIColor blackColor];
[self addSubview:shape];
return self;
}
@end
4

4 に答える 4

1

クラスメソッド:

  • インスタンスがないときに呼び出すことができます(まだ)
  • インスタンスを操作していないため(パラメーターとして渡されるか、メソッドによって作成されない限り)、特定のインスタンスのインスタンス変数にアクセスできません。
  • 単純な関数(前のポイントと一致する)とは異なり、サブクラスでオーバーライドできます

他の人が指摘しているように、あなたはいつもクラスメソッドを使っていると思います。他に何もない場合は、+alloc

于 2012-06-03T23:13:16.480 に答える
1

Class methods are simply methods that don't need objects. Therefore, any instance method that doesn't use its object could be a class method. The only time you must use a class method is when a method must be called without an object. alloc is a good example: it creates the object and returns it, so by definition there is no object when it is called.

One other use I've had for class methods (in C++ in embedded systems, so I don't have code to show) is to have a class keep a doubly-linked list of all its objects. (This is useful for debugging dumps; in embedded development your debugging tools are often just some kind of printf.)

The class has two members which are pointers to the first and last elements of the list, and the constructor and destructor insert and remove an object from the list. The functions to access the first and last objects are class methods, since you call those when you want to traverse the list of objects but don't have an object yet.

于 2012-06-03T23:13:22.580 に答える
1

Class methods have several uses:

  • As you've heard, they're essential for creating new objects. Creating objects is a two step process: first, you allocate memory for the object using the +alloc class method, then you initialize the object using some instance method that usually begins with -init. The +alloc method must be a class method because you don't have an instance upon which to call it; you only know the class name. The -init method should be an instance method, because +alloc returns an instance, an you want to initialize the properties unique to that instance, not to the entire class. So, you used a class method then an instance method in your code above: UIView *shape = [[UIView alloc] initWithFrame:CGRectMake(xVal, yVal, 10, 10)];

  • Class methods are useful for retrieving singletons, or shared instances of a class. For example, the NSUserDefaults class stores preferences and settings associated with your app. In most cases, people like to use a single set of preferences for their entire app, so it has a class method +standardUserDefaults that returns a single instance of NSUserDefaultsthat everyone can use at any point in the app's lifetime to get all the preferences associated with an app. Without that singleton and class method, you'd have to create and pass around an instance of NSUserDefaults throughout your app, which gets messy. Other examples include +[UIDevice currentDevice] and +[NSFileManager defaultManager].

  • Class methods are great for returning data or properties shared by all instances of the class. For example, UIView has a class method +layerClass that returns the kind of layer the view hosts. Since all instances of a particular UIView subclass use the same kind of layer, it has nothing to do with individual instances and thus makes sense as a class method.

  • You'll see a lot of class methods called "convenience methods." These methods (generally) combine calls to +alloc and -init and return an autoreleased instance of a class. For example, you can save some typing by writing [NSArray arrayWithObjects:...] instead of [[[NSArray alloc] initWithObjects:...] autorelease]. If you're using ARC, these convenience methods are less useful, but they are still everywhere in Cocoa.

  • Class methods are also sometimes used for utility classes, or classes that don't have state, and just have a bunch of methods that take in all the parameters they need. For example, you might have a method like +[PhoneUtilities parseAreaCodeFromPhoneNumber:string]. There are not many of these methods built-in to Cocoa; some people argue that it's better to make them regular C functions, singletons, or regular objective-c classes with instance methods.

I'm sure there are more, but that should give you some ideas.

于 2012-06-03T23:16:26.757 に答える
0

私の答えは、クラスメソッドは、いくつかのユーティリティ関数/メソッドを実行する必要があり、特定のインスタンスまたはオブジェクトに対してアクションを実行する必要が ない場合に非常に役立つということです。

たとえば、私自身のコードでは、通常、クラスでクラスメソッドを実行します。このクラスでは、メソッドを呼び出すことができるオブジェクトに関係なく、結果は同じになります。好き:

例えば

@interface MyAppCacheFiles
    + (NSURL *) getFileURLOfLocalCache;
@end

これらは、便利な方法と見なすこともできます(たとえば、NSString +stringWithFormat:またはのようにNSArray +arrayWithArray:)。

于 2012-06-03T22:36:07.497 に答える