Search code examples
iosobjective-cbluetoothcore-bluetooth

"Assignment to read-only property" error while setting up Core Bluetooth Peripheral Manager Services and Characteristics


I'm following the Apple Core Bluetooth programming guide, trying to set up a peripheralManager which will advertise certain data. I've written the following code based on the guide at https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonPeripheralRoleTasks/PerformingCommonPeripheralRoleTasks.html#//apple_ref/doc/uid/TP40013257-CH4-SW1

 _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:nil];
CBUUID *myConnectUUID = [CBUUID UUIDWithString:@"277860A8-9941-465B-9E75-F77F935299E7"];
CBUUID *advertiseUUID = [CBUUID UUIDWithString:@"C223B374-18FF-4D0B-8B46-B7CEC9C85077"];

_myCharacteristic =
[[CBMutableCharacteristic alloc] initWithType:advertiseUUID
                                   properties:CBCharacteristicPropertyRead
                                        value:nil permissions:CBAttributePermissionsReadable];

_myService = [[CBMutableService alloc] initWithType:myConnectUUID primary:YES];
_myService.characteristics = @[_myCharacteristic];
[_peripheralManager addService:_myService];

However, on the line

_myService.characteristics = @[_myCharacteristic];

I get an Xcode error which says "assignment to read-only property." I'm not sure what the issue is, since I directly followed the instructions, and am initializing the service/characteristic correctly. Does anyone have any advice?

Declaration of _myservice in .h file:

@property (strong, nonatomic) CBService *myService;

Solution

  • The problem is this line:

    @property (strong, nonatomic) CBService *myService;
    

    You have declared _myService as a CBService, so it is not mutable as far as the compiler knows. Thus, for _myService, characteristics is not assignable.

    You should have written

    CBMutableService* service = [[CBMutableService alloc] initWithType:myConnectUUID primary:YES];
    service.characteristics = @[_myCharacteristic];
    _myService = service;