English 中文(简体)
1. 私人单位:@interface or @implementation
原标题:Private ivar in @interface or @implementation

是否有理由在<条码>@interface上而不是在<条码>上宣布一个私人企业。

我在互联网上看到这样的代码(包括http://developer.apple.com/library/ios/pdocumentation/cocoa/conceptual/objectivec/ chapters/ocDefiningClahas.html“rel=“noreferer”>Apple ):

Foo.h

@interface Foo : NSObject {
@private
    id _foo;
}
@end

<Foo.m

@implementation Foo
// do something with _foo
@end

头号档案界定了某类人员的公开接口,而私人企业则......完全是私人的。 因此,为什么不宣布这样做?

Foo.h

@interface Foo : NSObject
@end

<Foo.m

@implementation Foo {
@private
    id _foo;
}

// do something with _foo
@end
最佳回答

Declaring instance variables in the @implementation is a recent feature of Obj-C, this is why you see a lot of code with them in the @interface - there was no other choice.

如果你使用一个汇编器,支持声明书状变量的实施,宣布这些变量很可能是最佳的缺省,那么,如果需要他人查阅,就只能将其放在接口中。

www.un.org/Depts/DGACM/index_spanish.htm Edit: Additionalfo

Instance variables declared in the implementation are implicitly hidden (effectively private) and the visibility cannot be changed - @public, @protected and @private do not produce compiler errors (with the current Clang at least) but are ignored.

问题回答

如果您需要针对旧系统或X代码的发布工作的汇编者支持的话,你将赞成@interface

If you are certain you will not need that backwards compatibility, I d say it s best to place it in the @implementation.

  • I think @private is a good default.
  • It minimizes compile times, and reduces dependencies if you use it right.
  • You can reduce much of that noise at the top of your header. Many people will put #imports for their ivars, but they should use a forward declaration as default. So you can remove many #imports and many forward declarations from your header.

The directives @public, @protected, and @private are not binding in objective-C, they are compiler hints about the accessibility of the variables. It DOES NOT RESTRICT YOU from accessing them.

例如:

@interface Example : Object
{
@public
int x;
@private
int y;
}
...


...
id ex = [[Example alloc ] init];
ex->x = 10;
ex->y = -10;
printf(" x = %d , y = %d 
", ex->x , ex->y );
...

gcc 编织物:

Main.m:56:1: 警告:可变的“y”是@ private;这将是未来的一个硬错误。

Main.m:57:1: 警告:可变的“y”是@ private;这将是未来的一个硬错误。

once for each "innapropriate" access to "private" member y, but compiles it anyway.

当你出面时

x = 10 , y = -10

So it really is up to you NOT to write access code this way, but because objc is a superset of C, C syntax works just fine, and all classes are transparent.

你可以设立汇编者,将这些警告作为错误和保释处理——但目标C并不是为了这种严格性而在内部建立。 动态方法的发送必须检查每次电话(Sloooowwwww.......)的范围和许可,因此,除了汇编时间的警告外,该系统期望方案者尊重数据成员的范围。

There are several tricks to getting privacy of members in objective-C. One is to make sure you put the interface and implementations of your class in separate .h and .m files, respectively, and put the data members in the implementation file (the .m file). Then the files that import the headers do not have access to the data members, only the class itself. Then provide access methods (or not) in the header. You can implement setter/getter functions in the implementation file for diagnostic purposes if you want and they will be callable, but direct access to the data members will not be.

例如:

@implementation Example2 :Object
{ 
 //nothing here
}
double hidden_d; // hey now this isn t seen by other files.
id classdata;    // neither is this.

-(id) classdata { return [classdata data]; } // public accessor
-(void) method2 { ... }
@end

// this is an "informal category" with no @interface section
// these methods are not "published" in the header but are valid for the class

@implementation Example2 (private)
-(void)set_hidden_d:(double)d { hidden_d = d; }

// You can only return by reference, not value, and the runtime sees (id) outside this file.
// You must cast to (double*) and de-reference it to use it outside of this file. 
-(id) hidden_d_ptr { return &hidden_d;}
@end

...
[Main.m]
...
ex2 = [[Example2 alloc] init];

double d = ex2->hidden_d; // error:  struct Example2’ has no member named ‘hidden_d’
id data = ex2->classdata; // error:  struct Example2’ has no member named ‘classdata’
id data = [ex2 classdata] // OK

[ex2 set_hidden_d : 6.28318 ]; // warning: Example2  may not respond to  -set_hidden_d: 

double* dp = [ex2 hidden_d_ptr]; // (SO UGLY)  warning: initialization from incompatible pointer type
                                 // use (double*)cast -- <pointer-to-pointer conversion>  
double d = (*dp); // dereference pointer (also UGLY). 

...

The compiler will issue warnings for such blatant shenanigans, but will go ahead and trust that you know what you are doing (really?), and that you have your reasons (do you?). Seem like a lot of work? Error Prone? Yay Baby! Try refactoring your code first before resorting to magic C tricks and meatball surgery like this.

But there it is. Good luck.





相关问题
Asynchronous request to the server from background thread

I ve got the problem when I tried to do asynchronous requests to server from background thread. I ve never got results of those requests. Simple example which shows the problem: @protocol ...

objective-c: Calling a void function from another controller

i have a void, like -(void) doSomething in a specific controller. i can call it in this controller via [self doSomething], but i don t know how to call this void from another .m file. I want to call ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

NSUndoManager and runModalForWindow:

I have a simple Core Data app which displays a list of entities in the main window. To create or add new entities, I use a second modal window with a separate managed object context so changes can be ...

NSMutableArray values becoming "invalid"

I m trying to show a database information in a tableview and then the detailed information in a view my problem is as follow: I created a NSMutableArray: NSMutableArray *myArray = [[NSMutableArray ...

iPhone numberpad with decimal point

I am writing an iPhone application which requires the user to enter several values that may contain a decimal point (currency values, percentages etc.). The number of decimal places in the values ...

热门标签