Binh Le
Binh Le

Reputation: 363

Is it allowed to duplicate variable name in same class?

I have a block of source code getting from Github. It looks like:

Header file

@interface VTDUpcomingDisplayData : NSObject

@property (nonatomic, readonly, copy,) NSArray*    sections;   // array of VTDUpcomingDisplaySection

+ (instancetype)upcomingDisplayDataWithSections:(NSArray *)sections;

@end

Implementation file

#import "VTDUpcomingDisplayData.h"


@interface VTDUpcomingDisplayData()
@property (nonatomic, copy) NSArray*    sections;
@end


@implementation VTDUpcomingDisplayData

+ (instancetype)upcomingDisplayDataWithSections:(NSArray *)sections
{
    VTDUpcomingDisplayData* data = [[VTDUpcomingDisplayData alloc] init];

    data.sections = sections;


    return data;
}

This block code has two variable name called 'sections' but builds successfully. I have two questions:

Upvotes: 0

Views: 131

Answers (2)

larva
larva

Reputation: 5148

It's normal in Objective-C, called override property attribute or redeclaring a property. You can declare a property is readonly in interface, and make it's readwrite (There’s no need to specify the readwrite attribute explicitly, but in this case You better write it) in implement.

Here's Apple document about redeclaring a property in class extension

Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself. It’s common, for example, to define a property as readonly in the interface, but as readwrite in a class extension declared above the implementation, in order that the internal methods of the class can change the property value directly.

  • First of all, I do not understand why this is allowed to happen?

    Just because it's normal behavior in Objective-C

  • Second, how to call exact the variable I want in source code?

    It's just once property, You can access it as readwrite in internal method. But in other class it's still readonly

Upvotes: 2

mttrb
mttrb

Reputation: 8345

Both declarations refer to the same property (and underlying instance variable).

However, the properties are declared differently in the header and the implementation. In the header, which defines the interface to be used by callers of this object, the property is declared readonly. In the implementation of the class the same property is missing the readonly attribute, i.e. it is read/write.

This is to allow the implementation of the class read and write access to the property but limit users of the class to only read from the property. Everybody is accessing the same property (instance variable), the only difference is the access rights of the different callers.

Upvotes: 0

Related Questions