Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - On lazy instantiation and convenience methods

Assume you have a Singleton Constants class, instance of which you'd like to use throughout your application.

In someClass, therefore we can reference [Constants instance] someCleverConstant];

Typing this gets old really quick and it would be nice to get a shortcut to the instance.

  • In someClass, we can declare @property (nonatomic, weak, readonly) Constants *constants;
  • And a getter to the instance
-(Constants*) constants {
  if (constants == nil) 
    constants = [Constants instance];
  return constants;
}

This way in someClass, therefore we can reference constants.someCleverConstant; instead

A few questions on this:

  • Is what i described a reasonable approach?
  • Is it correct to declare a property weak?
  • Is there any performance concerns with what i have described? Would it actually be better to call instance directly?
  • Consider a situation where you have 20 classes, each needing it's own pointer to Constants instance. Would this approach work then?

Thank you for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Following @vinceburn I would use the following example for constants and a singleton for more complex structures.

// Constants.h
// Replace PSMyApp for something more useful. e.g. company/name initials followed by app/class

// String example
NSString * const PSMyAppString = @"constantString"; 

// Logically related integers
typedef enum {
   PSMyAppRelatedValuesOne = 0,
   PSMyAppRelatedValuesTwo,
   PSMyAppRelatedValuesThree
} PSMyAppRelatedValues;

// Float example
const CGFloat PSMyAppFloat = 0.3f;

// Integer that has no related values
const NSInteger PSMyAppInteger = 2;

I prefer this over #define as I get auto completion and compiler checking and it fits more naturally with the way Apple does thing in some of the UIKit classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...