'Inserting objective-c sample code sections into a working xCode objective-c IOS project

I am trying to implement an answer to an old question.

Here is that answer https://stackoverflow.com/a/26725721/1984167

And here are the code sections suggested in that answer:

self.name = self.peripheral.name;
[self.peripheral addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqualToString:@"name"]) {
        [self peripheralDidUpdateName:self.peripheral];
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}


- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral {
    if([peripheral.name isEqualToString:self.name]) return;
    if([self.delegate respondsToSelector:@selector(peripheralDidUpdateName:)]) {
        [self.delegate peripheralDidUpdateName:self];
    }
}

I am using xCode 13.2.1 and my project has been operational for years but recently Bluetooth peripheral renaming has been become an issue which I need to solve.

First, I do not know for sure where I need to place the two lines that adds an observer.

I have tried adding the 2 observer creation lines in my ViewContoller.c code:

  1. The code section where its global variables are defined
  2. In its @interface section
  3. In its viewDidLoad

Unfortunately all 3 locations had different compiling errors, none of which I could solve.

After I have help placing those two lines of code it also looks like I will need help concerning errors in the use of the 'self' keyword.

I am a novice objective-c programmer and I do not understand how to implement the 'Self' Keyword as used by this sample code into my project.

I have searched and tried to understand 'Self' Keyword usage so that I can modify the code sample for use in my project but I get lost in the subtleties of when/where and for what purpose 'self' serves.

I think that if someone helps me with 'where to put the two lines that add an observer' and with the 'self' usage issue, I may be able to actually understand how this code can get compiled into my project so I can test it.

Thanks Dale



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source