For some reason NSString objects just won't go into an NSMutableSet
The set remains empty - count stays 0 and firstInHandler is never called
I have tried everything..!
If anyone has any idea why I would greatly appreciate the help
VCKeySet.h
#import <Foundation/Foundation.h>
#interface VCKeySet : NSObject
{
void (^firstInHandler)();
void (^lastOutHandler)();
}
#property (atomic, readonly, strong) NSMutableSet* keys;
- (id) initWithFirstInHandler:(void(^)()) firstInHandler_ withLastOutHandler:(void(^)()) lastOutHandler_;
- (void) add:(NSString*) key_;
- (void) remove: (NSString*) key_;
- (BOOL) has: (NSString*) key;
#end
VCKeySet.m
#import "VCKeySet.h"
#implementation VCKeySet
#synthesize keys;
- (id) initWithFirstInHandler: (void(^)()) firstInHandler_ withLastOutHandler: (void(^)()) lastOutHandler_
{
if(self=[self init])
{
firstInHandler = firstInHandler_;
lastOutHandler = lastOutHandler_;
}
return self;
}
- (void) add:(NSString*) key_
{
for(NSString* key in self.keys)
{
if([key isEqualToString:key_])
{
return;
}
}
[self.keys addObject:key_];
if([self.keys count] == 1)
{
firstInHandler();
}
}
- (void) remove: (NSString*) key_
{
for(NSString* key in keys)
{
if([key isEqualToString:key_])
{
[keys removeObject:key];
if([keys count] == 0)
{
lastOutHandler();
}
}
}
}
- (BOOL) has: (NSString*) key_
{
for(NSString* key in keys)
{
if([key isEqualToString:key_])
{
return YES;
}
}
return NO;
}
#end
Here is how I try to add a key to the set
VCKeySet* lock = [[VCKeySet alloc] initWithFirstInHandler:^()
{
NSLog(#"Adding UI lock");
[application beginIgnoringInteractionEvents];
}
withLastOutHandler:^()
{
NSLog(#"Removing UI lock");
[application endIgnoringInteractionEvents];
}];
[lock add:#"InitialiseApp"];
Thanks
The problem is, you never allocate and initialize your set.
Refactor your add: method to look something like this:
- (void) add:(NSString*) key_ {
if (!self.keys) {
_keys = [[NSMutableSet alloc] init];
}
[self.keys addObject:key_];
if([self.keys count] == 1) {
firstInHandler();
}
}
Related
after tweaking the code i reduced 3 errors into 2 but I'm still unsure how to resolve the final errors.
-No known class method for selector 'getExportedModuleForName:'
-No known class method for selector 'getExportedModule:'
#import <UMReactNativeAdapter/UMReactNativeEventEmitter.h>
#import <UMCore/UMEventEmitter.h>
#import <UMCore/UMExportedModule.h>
#import <UMCore/UMModuleRegistry.h>
#interface UMReactNativeEventEmitter ()
#property (nonatomic, assign) int listenersCount;
#property (nonatomic, weak) UMModuleRegistry *ModuleRegistry;
#property (nonatomic, strong) NSMutableDictionary<NSString *, NSNumber *> *modulesListenersCounts;
#end
#implementation UMReactNativeEventEmitter
- (instancetype)init
{
if (self = [super init]) {
_listenersCount = 0;
_modulesListenersCounts = [NSMutableDictionary dictionary];
}
return self;
}
UM_REGISTER_MODULE();
+ (NSString *)moduleName
{
return #"UMReactNativeEventEmitter";
}
+ (const NSArray<Protocol *> *)exportedInterfaces
{
return #[#protocol(UMEventEmitterService)];
}
- (NSArray<NSString *> *)supportedEvents
{
NSMutableSet<NSString *> *eventsAccumulator = [NSMutableSet set];
for (UMExportedModule *exportedModule in [UMModuleRegistry getAllExportedModules]) {
if ([exportedModule conformsToProtocol:#protocol(UMEventEmitter)]) {
id<UMEventEmitter> eventEmitter = (id<UMEventEmitter>)exportedModule;
[eventsAccumulator addObjectsFromArray:[eventEmitter supportedEvents]];
}
}
return [eventsAccumulator allObjects];
}
RCT_EXPORT_METHOD(addProxiedListener:(NSString *)moduleName eventName:(NSString *)eventName)
{
[self addListener:eventName];
// Validate module
UMExportedModule *module = [UMModuleRegistry getExportedModuleForName:moduleName];
if (RCT_DEBUG && module == nil) {
UMLogError(#"Module for name `%#` has not been found.", moduleName);
return;
} else if (RCT_DEBUG && ![module conformsToProtocol:#protocol(UMEventEmitter)]) {
UMLogError(#"Module `%#` is not an UMEventEmitter, thus it cannot be subscribed to.", moduleName);
return;
}
// Validate eventEmitter
id<UMEventEmitter> eventEmitter = (id<UMEventEmitter>)module;
if (RCT_DEBUG && ![[eventEmitter supportedEvents] containsObject:eventName]) {
UMLogError(#"`%#` is not a supported event type for %#. Supported events are: `%#`",
eventName, moduleName, [[eventEmitter supportedEvents] componentsJoinedByString:#"`, `"]);
}
// Global observing state
_listenersCount += 1;
if (_listenersCount == 1) {
[self startObserving];
}
// Per-module observing state
int newModuleListenersCount = [self moduleListenersCountFor:moduleName] + 1;
if (newModuleListenersCount == 1) {
[eventEmitter startObserving];
}
_modulesListenersCounts[moduleName] = [NSNumber numberWithInt:newModuleListenersCount];
}
RCT_EXPORT_METHOD(removeProxiedListeners:(NSString *)moduleName count:(double)count)
{
[self removeListeners:count];
// Validate module
UMExportedModule *module = [UMModuleRegistry getExportedModuleForName:moduleName];
if (RCT_DEBUG && module == nil) {
UMLogError(#"Module for name `%#` has not been found.", moduleName);
return;
} else if (RCT_DEBUG && ![module conformsToProtocol:#protocol(UMEventEmitter)]) {
UMLogError(#"Module `%#` is not an UMEventEmitter, thus it cannot be subscribed to.", moduleName);
return;
}
id<UMEventEmitter> eventEmitter = (id<UMEventEmitter>)module;
// Per-module observing state
int newModuleListenersCount = [self moduleListenersCountFor:moduleName] - 1;
if (newModuleListenersCount == 0) {
[eventEmitter stopObserving];
} else if (newModuleListenersCount < 0) {
UMLogError(#"Attempted to remove more `%#` listeners than added", moduleName);
newModuleListenersCount = 0;
}
_modulesListenersCounts[moduleName] = [NSNumber numberWithInt:newModuleListenersCount];
// Global observing state
if (_listenersCount - 1 < 0) {
UMLogError(#"Attempted to remove more proxied event emitter listeners than added");
_listenersCount = 0;
} else {
_listenersCount -= 1;
}
if (_listenersCount == 0) {
[self stopObserving];
}
}
# pragma mark Utilities
- (int)moduleListenersCountFor:(NSString *)moduleName
{
NSNumber *moduleListenersCountNumber = _modulesListenersCounts[moduleName];
int moduleListenersCount = 0;
if (moduleListenersCountNumber != nil) {
moduleListenersCount = [moduleListenersCountNumber intValue];
}
return moduleListenersCount;
}
# pragma mark - UMModuleRegistryConsumer
- (void)setModuleRegistry:(UMModuleRegistry *)moduleRegistry
{
moduleRegistry = moduleRegistry;
}
#end
I know little to nothing about Objective-c so any help is appreciated a code example is double appreciated!
I want to check if the user has an open basket if so send them to the menu if not then send send them to my open basket view but i m getting an error.
So my question is how to get rid of this problem ? and is my logic right ?
'NSInvalidArgumentException', reason: '-[Merchant merchantId]: unrecognized selector sent to instance 0x7fad19529490'.
i m using this method to check for open baskets when the button addToOrderButtonTapped is press in the menuview
[[OrderManager sharedManager]getBasketsForMerchant:merchant success:^(NSArray *baskets) {
for (Basket *basket in baskets){
if ([basket.status isEqualToString:kBasketStatusOpen]) {
[self.openBaskets addObject:basket];
}
}if (self.openBaskets.count > 0){
self.openBaskets = self.openBaskets;
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:kSegueMenu sender:self];
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:KSegueOpenBasket sender:self];
});
}
} failure:^(NSError *error, NSHTTPURLResponse *response) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *localizedString = NSLocalizedString(#"Order.ErrorLoadingOpenOrders", "Get error message");
[self showMessage:localizedString withTitle:MessageTypeError];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
});
}];
The menuview
//
// MenuItemViewController.m
// BaseApp
//
#import "MenuItemViewController.h"
#import "RoundedButton.h"
#import "MenuOptionCell.h"
#import "MenuItem.h"
#import "MenuOptionButton.h"
#import "MenuChoice.h"
#import "OrderManager.h"
#import "TypeOfChoiceCell.h"
#import "MenuOption.h"
#import "OrderPricingTableViewCell.h"
#import "RKManagedObjectStore.h"
#import "NSManagedObjectContext+RKAdditions.h"
#import "MerchantManager.h"
#import "Merchant.h"
#import "OrdersViewController.h"
#import "MenuItem.h"
#import "MenuViewController.h"
#import "OrderConfirmationViewController.h"
#import "OrderManager.h"
#import "APIClient.h"
#import "MenuManager.h"
#import "DiscoverViewController.h"
#import "DiscoverCollectionViewCell.h"
#import "MerchantManager.h"
#import "MenuViewController.h"
#import "MenuManager.h"
#import "MerchantDetailsViewController.h"
#import "OpenOrdersViewController.h"
typedef NS_ENUM(NSUInteger, MenuOptionsSection) {
MenuOptionsSectionRequired = 0,
MenuOptionsSectionOptional = 1
};
static NSString *const OpenBasketsSegue = #"OpenBaskets";
static NSString *const kSegueMenu = #"ShowMenu";
static NSString *const KSegueOpenBasket = #"OpenBaskets";
#interface MenuItemViewController () <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, weak) IBOutlet UILabel *menuItemName;
#property (nonatomic, weak) IBOutlet UILabel *quantityLabel;
#property (nonatomic, weak) IBOutlet UILabel *menuItemPrice;
#property (nonatomic, weak) IBOutlet UILabel *subTotalLabel;
#property (nonatomic, weak) IBOutlet UITextView *menuItemDescription;
#property (nonatomic, weak) IBOutlet RoundedButton *addToOrderButton;
#property (nonatomic, weak) IBOutlet UITableView *tableView;
#property (nonatomic, weak) IBOutlet UIView *cartView;
#property (nonatomic, weak) IBOutlet UIButton *subtractButton;
#property (nonatomic) NSDecimalNumber *temporarySubtotal;
#property (nonatomic, strong) NSMutableArray<MenuOption *> *requiredChoices;
#property (nonatomic, strong) NSMutableArray<MenuOption *> *optionalChoices;
#property (nonatomic, strong) NSMutableArray<NSMutableArray *> *optionChoicesSection;
#property (nonatomic, strong) NSMutableArray<NSDictionary *> *options;
#property (nonatomic, strong) NSMutableArray <Basket *>*openBaskets;
#property (nonatomic) BOOL launchViewFirstTime;
#end
#implementation MenuItemViewController
#pragma - Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = #"Menu Item";
self.menuItemName.text = self.menuCategory.selectedBasketLine.menuItem.name;
self.menuItemPrice.text = [NSString stringWithFormat:#"%#", [Basket formattedCurrencyStringForAmount:self.menuCategory.selectedBasketLine.menuItem.price]];
self.quantityLabel.text = self.menuCategory.selectedBasketLine.quantity.stringValue;
self.temporarySubtotal = [self calculateTemporarySubtotal:[OrderManager sharedManager].currentBasket.subtotal menuItemPrice:self.menuCategory.selectedBasketLine.menuItem.price];
[self setSubtotalText:self.temporarySubtotal];
self.menuItemDescription.text = self.menuCategory.selectedBasketLine.menuItem.menuItemDescription;
self.subtractButton.alpha = 0.65;
self.requiredChoices = [[NSMutableArray alloc] init];
self.optionalChoices = [[NSMutableArray alloc] init];
self.optionChoicesSection = [[NSMutableArray alloc] init];
self.options = [[NSMutableArray alloc] init];
[self initializeChoiceArrays];
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.launchViewFirstTime = YES;
if (self.optionChoicesSection.count > 0) {
[self.tableView reloadData];
} else {
self.tableView.hidden = YES;
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.launchViewFirstTime = NO;
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
for (MenuOption *menuOption in self.requiredChoices) {
[menuOption resetNumberOfChoicesSelected];
}
for (MenuOption *menuOption in self.optionalChoices) {
[menuOption resetNumberOfChoicesSelected];
}
self.menuCategory = nil;
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[self.menuItemDescription setContentOffset:CGPointZero animated:YES];
}
#pragma - IBActions
- (IBAction)addButtonTapped:(id)sender {
NSInteger count = self.quantityLabel.text.integerValue;
count++;
if (count > 1) {
self.subtractButton.alpha = 1;
}
NSDecimalNumber *newSubTotal = [self.temporarySubtotal decimalNumberByAdding:self.menuCategory.selectedBasketLine.menuItem.price];
[self modifyCurrentBasketSubtotal:newSubTotal quantity:count];
}
- (IBAction)subtractButtonTapped:(id)sender {
NSInteger count = self.quantityLabel.text.integerValue;
if (count > 1) {
count--;
NSDecimalNumber *newSubTotal = [self.temporarySubtotal decimalNumberBySubtracting:self.menuCategory.selectedBasketLine.menuItem.price];
[self modifyCurrentBasketSubtotal:newSubTotal quantity:count];
if (count == 1) {
self.subtractButton.alpha = 0.65;
}
}
}
- (IBAction)addToOrderButtonTapped:(id)sender {
MenuOption *menuOption;
Merchant *merchant = [[Merchant alloc]init];
// First check if there are any missing required options that have to be selected
if ((menuOption = [self checkMissingRequiredOptionsHaveBeenSelected])) {
NSString *localizedString = NSLocalizedString(#"AddMenuItem.RequiredChoicesNotSelected", #"Get string for error");
NSString *formattedString = [NSString stringWithFormat:localizedString, menuOption.name];
[self showMessage:formattedString withTitle:MessageTypeError];
return;
}
// Now check if the minimum and maximum choice seletion have been met for the menu options
if ((menuOption = [self validateMinMaxForMenuOptionsHaveBeenMet])) {
NSString *localizedString = NSLocalizedString(#"AddMenuItem.MinMaxNotFulfilled", #"Get string for error");
NSString *formattedString = [NSString stringWithFormat:localizedString, menuOption.name];
[self showMessage:formattedString withTitle:MessageTypeError];
return;
}
// Add the menu item to the basket
if (self.menuItemAddedBlock) {
self.menuItemAddedBlock(self, self.menuCategory);
// [self dismissViewControllerAnimated:YES completion:nil];
//checking for open basket here
[[OrderManager sharedManager]getBasketsForMerchant:merchant success:^(NSArray *baskets) {
for (Basket *basket in baskets){
if ([basket.status isEqualToString:kBasketStatusOpen]) {
[self.openBaskets addObject:basket];
}
}if (self.openBaskets.count > 0){
self.openBaskets = self.openBaskets;
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:kSegueMenu sender:self];
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self performSegueWithIdentifier:KSegueOpenBasket sender:self];
});
}
} failure:^(NSError *error, NSHTTPURLResponse *response) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *localizedString = NSLocalizedString(#"Order.ErrorLoadingOpenOrders", "Get error message");
[self showMessage:localizedString withTitle:MessageTypeError];
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
});
}];
}
}
- (IBAction)cancelButtonTapped:(UIBarButtonItem *)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.optionChoicesSection.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.optionChoicesSection[section].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MenuOptionCell *cell = (MenuOptionCell *)[tableView dequeueReusableCellWithIdentifier:[MenuOptionCell reuseIdentifier]];
cell.menuOption = self.optionChoicesSection[indexPath.section][indexPath.row];
cell.menuOptionCellButtonPressedBlock = ^(MenuOptionButton *button, MenuOption *option, MenuChoice *choice) {
[self adjustSelectedOptions:option choice:choice indexPath:indexPath];
};
cell.menuOptionCellDefaultOptionDetectedBlock = ^(MenuOptionButton *button, MenuOption *option, MenuChoice *choice) {
[self adjustSelectedOptions:option choice:choice indexPath:indexPath];
};
cell.menuOptionCellDeselectedBlock = ^(MenuOptionButton *button, MenuOption *option, MenuChoice *choice) {
[self adjustSelectedOptions:option choice:choice indexPath:indexPath];
};
[cell configureCell:self.launchViewFirstTime];
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
TypeOfChoiceCell *cell = (TypeOfChoiceCell *)[tableView dequeueReusableCellWithIdentifier:[TypeOfChoiceCell reuseIdentifier]];
switch ((MenuOptionsSection)section) {
case MenuOptionsSectionRequired:
if (self.requiredChoices.count > 0) {
cell.title = NSLocalizedString(#"AddMenuItem.RequiredChoiceText", #"Get string for title");
return cell;
} else if (self.optionalChoices.count > 0) {
cell.title = NSLocalizedString(#"AddMenuItem.OptionalChoiceText", #"get string for title");
return cell;
}
case MenuOptionsSectionOptional:
if (self.optionalChoices.count > 0) {
cell.title = NSLocalizedString(#"AddMenuItem.OptionalChoiceText", #"Get string for title");
return cell;
}
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
MenuOption *option = self.optionChoicesSection[indexPath.section][indexPath.row];
return [MenuOptionCell heightForMenuOption:option];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return [TypeOfChoiceCell height];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0.01f;
}
#pragma - Helpers
- (void)setSubtotalText:(NSDecimalNumber *)subtotal {
if (!subtotal) {
self.subTotalLabel.text = NSLocalizedString(#"AddMenuItem.SubtotalDefault", #"Get string for subtotal");
} else {
NSString *localizedString = NSLocalizedString(#"AddMenuItem.SubtotalFormatted", #"Get string for subtotal");
self.subTotalLabel.text = [NSString stringWithFormat:localizedString, [Basket formattedCurrencyStringForAmount:subtotal]];
}
}
- (void)modifyCurrentBasketSubtotal:(NSDecimalNumber *)subtotal quantity:(NSInteger)quantity {
self.menuCategory.selectedBasketLine.quantity = [NSNumber numberWithInteger:quantity];
self.menuCategory.selectedBasketLine.subtotal = subtotal;
self.temporarySubtotal = subtotal;
[self setSubtotalText:subtotal];
self.quantityLabel.text = self.menuCategory.selectedBasketLine.quantity.stringValue;
}
- (NSDecimalNumber *)calculateTemporarySubtotal:(NSDecimalNumber *)orderManagerSubTotal menuItemPrice:(NSDecimalNumber *)menuItemPrice {
if (orderManagerSubTotal == 0) {
return menuItemPrice;
} else {
return [orderManagerSubTotal decimalNumberByAdding:menuItemPrice];
}
}
- (MenuOption *)checkMissingRequiredOptionsHaveBeenSelected {
for (MenuOption *menuOption in self.requiredChoices) {
if (!menuOption.selected) {
return menuOption;
}
}
return nil;
}
- (MenuOption *)validateMinMaxForMenuOptionsHaveBeenMet {
for (MenuOption *menuOption in self.requiredChoices) {
if ([menuOption validateIndividualMinMaxForMenuOption]) {
return menuOption;
}
}
for (MenuOption *menuOption in self.optionalChoices) {
if (menuOption.selected) {
if ([menuOption validateIndividualMinMaxForMenuOption]) {
return menuOption;
}
}
}
return nil;
}
- (void)initializeChoiceArrays {
NSArray<MenuOption *> *menuOptions = [self.menuCategory.selectedBasketLine.menuItem.menuOptions allObjects];
for (MenuOption *menuOption in menuOptions) {
if (menuOption.minimumChoices == nil) {
menuOption.minimumChoices = [NSNumber numberWithInt:0];
}
if (menuOption.maximumChoices == nil) {
menuOption.maximumChoices = [NSNumber numberWithInt:0];
}
// For now make an optional choice required if minimumChoices > 0
if (menuOption.isRequired || [menuOption.minimumChoices intValue] > 0) {
menuOption.isRequired = YES;
[self.requiredChoices addObject:menuOption];
} else {
[self.optionalChoices addObject:menuOption];
}
}
if (self.requiredChoices.count > 0) {
[self.optionChoicesSection addObject:self.requiredChoices];
}
if (self.optionalChoices.count > 0) {
[self.optionChoicesSection addObject:self.optionalChoices];
}
}
- (void)adjustSelectedOptions:(MenuOption *)option choice:(MenuChoice *)choice indexPath:(NSIndexPath *)indexPath {
self.menuCategory.selectedBasketLine.subtotal = self.menuCategory.selectedBasketLine.menuItem.price;
if (option.selected && option.menuChoices.count == 0) {
[self.options addObject:#{kOption: option.menuOptionId ?: #"", kChoice: #""}];
if (option.price) {
self.temporarySubtotal = [self.temporarySubtotal decimalNumberByAdding:option.price];
}
if (option.isRequired) {
self.requiredChoices[indexPath.row].selected = option.selected;
self.requiredChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
} else {
self.optionalChoices[indexPath.row].selected = option.selected;
self.optionalChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
}
} else {
if (option.menuChoices.count == 0) {
[self.options removeObject:#{kOption: option.menuOptionId ?: #"", kChoice: #""}];
if (option.price) {
self.temporarySubtotal = [self.temporarySubtotal decimalNumberBySubtracting:option.price];
}
if (option.isRequired) {
self.requiredChoices[indexPath.row].selected = option.selected;
self.requiredChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
} else {
self.optionalChoices[indexPath.row].selected = option.selected;
self.optionalChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
}
}
}
if (choice.selected && option.menuChoices.count > 0) {
[self.options addObject:#{kOption: choice.menuOption.menuOptionId ?: #"", kChoice: choice.menuChoiceId ?: #""}];
if (choice.price) {
self.temporarySubtotal = [self.temporarySubtotal decimalNumberByAdding:choice.price];
}
if (option.isRequired) {
self.requiredChoices[indexPath.row].selected = choice.selected;
self.requiredChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
} else {
self.optionalChoices[indexPath.row].selected = choice.selected;
self.optionalChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
}
} else {
if (option.menuChoices.count > 0) {
[self.options removeObject:#{kOption: choice.menuOption.menuOptionId ?: #"", kChoice: choice.menuChoiceId ?: #""}];
if (choice.price) {
self.temporarySubtotal = [self.temporarySubtotal decimalNumberBySubtracting:choice.price];
}
if (option.isRequired) {
if ([option.numberOfChoicesSelected intValue] == 0) {
self.requiredChoices[indexPath.row].selected = option.selected;
} else {
self.requiredChoices[indexPath.row].selected = !choice.selected;
}
self.requiredChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
} else {
self.optionalChoices[indexPath.row].selected = choice.selected;
self.optionalChoices[indexPath.row].numberOfChoicesSelected = option.numberOfChoicesSelected;
}
}
}
[self setSubtotalText:self.temporarySubtotal];
self.menuCategory.selectedBasketLine.attributes = self.options;
}
#end
This is the line of code thats giving me the error
+ (void)getBasketsForMerchant:(Merchant *)merchant success:(void (^)(NSArray *basket))success failure:(void (^)(NSError *, NSHTTPURLResponse *))failure {
NSMutableDictionary* params = #{#"expand": #"merchant"}.mutableCopy;
if (merchant) {
params[#"merchant"] = merchant.merchantId;
}
[[RKObjectManager sharedManager] getObjectsAtPath:kOrdersEndpoint parameters:params success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
NSArray* items = mappingResult.array;
if (success) {
success(items);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
if (failure) {
failure(error, operation.HTTPRequestOperation.response);
} else {
_defaultFailureBlock(operation, error);
}
}];
}
This error:
'NSInvalidArgumentException', reason: '-[Merchant merchantId]: unrecognized selector sent to instance 0x7fad19529490'.
Means that you have an object at location 0x7fad19529490 and you tried to call "merchantId" on it. That object does not respond to merchantId.
So, look very carefully at the definition of Merchant. Did you get the spelling of merchantId right in fieldMappings? Is it merchantID with a capital D?
If you are sure that merchant has a property named merchantId exactly, then, the next likely thing is that the object at 0x7fad19529490 is not a Merchant.
The easiest thing to do is to add an exception breakpoint (use the +) at the bottom of the breakpoint navigator. When this exception happens, grab the pointer address from the error (it might be different each time) and see what it is in the debugger. To do that, at the (lldb) prompt, type:
po (NSObject*)(0x7fad19529490)
but use the address from the error. If it's a Merchant, I expect it to say something like:
<Merchant: 0x7fad19529490>
Or, if you have overridden description, it will be the output of that.
I have a Shearwell stick reader, which reads in cattle tags, sheep tags and goat tags via BLE. When connecting the BLE device, the device list shows up in the tableView of the SDLBluetoothConnectViewController then disappears. I am also not able to grab the information from the device using a segue. The bluetooth icon flashes 3 times and does not pair with the device. Can anyone see where my error is i've looked for hours!! thanks in advance!
here is the SDLStickreader.m
// A StickReader is a wrapper for a CBPeripheral that has been discovered using a filter for StickReader UUID.
#import "SDLStickReader.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReaderPrivate.h"
#import "SDLSerialPort.h"
//#import "SDLIdentifier.h"
#interface SDLStickReader () <SerialPortDelegate>
#property (strong, nonatomic) CBPeripheral *peripheral;
#end
#implementation SDLStickReader
static SDLStickReaderManager * _manager;
NSMutableData *_data;
SDLSerialPort *serialPort;
BOOL waitingForConfigInfo = YES;
NSMutableString *configString;
+(SDLStickReaderManager *)manager {
if (nil == _manager) {
_manager = [[SDLStickReaderManager alloc] init];
}
return _manager;
}
+ (instancetype)forPeripheral: (CBPeripheral *)peripheral {
return [[self alloc] initWithPeripheral:peripheral];
}
- (instancetype)initWithPeripheral: (CBPeripheral *)peripheral {
self = [super init];
if (self) {
_detail = #"";
self.peripheral = peripheral;
//peripheral.delegate = self;
__tagReadService = [CBUUID UUIDWithString:SDL_STICKREADER_TAGREAD_UUID];
if (peripheral.state == CBPeripheralStateConnected) {
NSLog(#"periperal is connected");
} else {
NSLog(#"periperal is NOT connected");
}
_data = [[NSMutableData alloc] init];
serialPort = [[SDLSerialPort alloc] initWithPeripheral:peripheral andDelegate:self];
peripheral.delegate = self;
[serialPort open ];
}
return self;
}
-(BOOL)hasPeripheral: (CBPeripheral *)peripheral {
return [self.peripheral isEqual: peripheral];
}
-(NSUUID *)identifier {
return self.peripheral.identifier;
}
-(NSString *)name {
return self.peripheral.name;
}
-(NSString *)description {
return [NSString stringWithFormat: #"Peripheral: %#", self.name];
}
-(NSString *)state {
switch (self.peripheral.state) {
case CBPeripheralStateConnected:
return SDL_STICKREADER_STATE_CONNECTED;
case CBPeripheralStateConnecting:
return SDL_STICKREADER_STATE_CONNECTING;
case CBPeripheralStateDisconnected:
return SDL_STICKREADER_STATE_DISCONNECTED;
}
}
// Every time the peripheral sends new data, it calls the delegate peripheral:didUpdateValueForCharacteristic:error: method. The second argument contains the characteristic that you can read.
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic: (CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(#"Error");
return;
}
if ([self.characteristics containsObject: characteristic.UUID]) {
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
// Have we got everything we need?
NSUInteger startOfEom = [stringFromData rangeOfString: SDL_STICKREADER_EOM].location;
if (NSNotFound == startOfEom) {
// it is not the EOM so append the data to what we have so far and wait for more.
[_data appendData: characteristic.value];
} else {
// contains EOM, so remove the
NSString *lastPart = [stringFromData substringToIndex:startOfEom];
NSString *message = [[NSString alloc] initWithData: _data encoding:NSUTF8StringEncoding];
if (nil != lastPart && lastPart.length > 0) {
message = [message stringByAppendingString:lastPart];
}
if (nil != self.listener) {
[self.listener stickReader:self didReadTag:message];
}
[_data setLength:0];
}
}
}
// Method that ensures that the CBCentral knows when a notification state for a given characteristic changes. Track it in order to understand when a characteristic state changes (update app values). You should check if the characteristic notification has stopped. If it has, you should disconnect from it:
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (![self.characteristics containsObject: characteristic.UUID]) {
return;
}
if (characteristic.isNotifying) {
NSLog(#"Notification began ");
} else {
// Notification has stopped
NSLog(#"Notification stopped ");
//[_manager cancelPeripheralConnection:peripheral];
}
}
/////////////////////////////////////////////////////////////////////////////////////
- (void) port: (SDLSerialPort*) serialPort event : (SPEvent) ev error: (NSInteger)err {
if (SP_EVT_OPEN == ev) {
//NSLog(#"serialPortOpened");
configString = [[NSMutableString alloc] init];
[serialPort write: [#"c\r" dataUsingEncoding: NSUTF8StringEncoding]];
} else {
NSLog(#"serialPortClosed");
}
}
- (void) writeComplete: (SDLSerialPort*) serialPort withError: (NSInteger)err {
NSLog(#"writeComplete");
}
- (void) port: (SDLSerialPort*) serialPort receivedData: (NSData*)data {
if (data.length > 0) {
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString: #"|()#"];
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"receivedData: %#", str);
if ([str hasPrefix: #"Shearwell"]) {
_detail = str;
//NSLog(#"updating: %#", str);
[[SDLStickReader manager] addedShearwellStickReader: self];
} else if (NSNotFound != [str rangeOfCharacterFromSet: charSet].location ) {
// Data
if (waitingForConfigInfo) {
[configString appendString:str];
if (NSNotFound != [configString rangeOfString: #"(cS)"].location) {
// got end of config string, parse config.
NSRange found = [configString rangeOfString: #"#18|"];
if (NSNotFound != found.location) {
NSRange getRange = NSMakeRange(found.location + found.length, 1);
NSString *str = [configString substringWithRange: getRange];
self.eidFormat = [str integerValue];
NSLog(#"StickReader format: %d", self.eidFormat);
}
waitingForConfigInfo = NO;
[serialPort write: [#"v\r" dataUsingEncoding: NSUTF8StringEncoding]];
}
} else {
// Users data
[self.listener stickReader:self didReadData: str];
}
} else {
// Tag
if (nil != self.listener) {
[self.listener stickReader:self didReadTag: str];
}
}
}
}
and my SDLBluetoothConnectViewController.m
#import "SDLBluetoothConnectViewController.h"
#import "SDLStickReaderManager.h"
#import "SDLStickReader.h"
#import "SDLViewController.h"
#interface SDLBluetoothConnectViewController () <UITableViewDataSource, UITableViewDelegate, SDLStickReaderManagerListener>
#property (weak, nonatomic) IBOutlet UITableView *stickReaderListView;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderNameLabel;
#property (strong, nonatomic) IBOutlet UILabel *stickReaderDescLabel;
#end
/*
This class starts the process of scanning in the 'viewDidLoad' method by setting the SDLStickReaderManager 'singleton' to self. When the scan button is pressed the SDLStickReaderManager scan is called, and each stick reader found is returned via the listener call. This listener call is used to refresh the table view.
When a user selects a stick reader from the list the StickReader view is started and passed the selected stick reader.
*/
#implementation SDLBluetoothConnectViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.stickReaderListView setDelegate: self];
[self.stickReaderListView setDataSource: self];
[SDLStickReader manager].listener = self;
[self.stickReaderListView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanButtonPressed:(id)sender {
[SDLStickReader.manager scan];
}
- (IBAction)cancelButtonPressed:(id)sender {
SDLStickReader.manager.listener = nil;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillDisappear:(BOOL)animated {
/*
Every time the view disappears, you should stop the scanning process.
*/
[SDLStickReader.manager stopScan];
}
/////////////////////////////////////////////////////////////////////////////////
/////// Table handling //////////////////////////////////////////////////////////
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
[SDLStickReader.manager stopScan];
[self performSegueWithIdentifier:#"deviceInfoSegue" sender:self];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
return stickReaders.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: simpleTableIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: simpleTableIdentifier];
}
NSArray *stickReaders = SDLStickReader.manager.discoveredStickReaders;
SDLStickReader * stickReader = [stickReaders objectAtIndex: indexPath.row];
NSString *desc = [stickReader name];
cell.textLabel.text = desc;
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"deviceInfoSegue"]) {
//some additional info here
}
}
////////////////////////////////////////////////////////////////////////////////// /
/// SDLStickReaderManager callbacks ///////////////////////////////////////////////
-(void)stickReader: (SDLStickReader *)stickReader addedToList: (NSArray *)discoveredStickReaders {
//NSLog(#"View StickReaderAdded");
[self.stickReaderListView reloadData];
//[SDLStickReader.manager connect: stickReader];
}
-(void)connectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader connected");
[self.stickReaderListView reloadData];
}
-(void)disconnectedStickReader: (SDLStickReader *)stickReader {
//NSLog(#"View StickReader disconnected");
[self.stickReaderListView reloadData];
}
I'm working with NSCache in Objective-C and Cocoa for iOS. Every time I restart the project, the getCacheRecommend call returns null and I expect it to return a value.
#import <Foundation/Foundation.h>
#class ASJsonDiscoverModel;
#interface ASUserCache : NSObject
+ (ASUserCache *)sharedInstance;
- (void)clear;
- (void)setCacheRecommend:(ASJsonDiscoverModel *)discover;
- (ASJsonDiscoverModel *)getCacheRecommend;
ASJsonDiscoverModel is my custom object class.
#import "ASUserCache.h"
#interface ASUserCache ()
#property (nonatomic,strong) NSCache *cache;
#end
#implementation ASUserCache
+ (ASUserCache *)sharedInstance
{
__strong static ASUserCache *cache = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
cache = [[ASUserCache alloc] init];
});
return cache;
}
- (instancetype)init
{
if (self = [super init]) {
_cache = [[NSCache alloc] init];
}
return self;
}
- (void)setCacheRecommend:(ASJsonDiscoverModel *)discover
{
NSString *key = #"channelRecommend";
[_cache removeObjectForKey:key];
[_cache setObject:discover forKey:key];
}
- (ASJsonDiscoverModel *)getCacheRecommend
{
NSString *key = #"channelRecommend";
return [_cache objectForKey:key];
}
- (void)clear
{
if (_cache) {
[_cache removeAllObjects];
}
}
- (NSString *)keyforUserID:(NSString *)userID
{
return [NSString stringWithFormat:#"**%#",userID];
}
I'm using an ARC enabled objective c version of protocol buffer and I have integrated it with XCode 4.5. I compiled a simple proto file, serialized and deserialized it to check if its working fine.
Now i added a "repeated" type field and i'm getting the following error -
ARC Semantic Issue: No visible #interface for "PBAppendableArray" declares the selector "objectAtIndex:"
My proto file -
message Person
{
required int32 id=1;
required string name=2;
repeated string email=3;
}
Person.pb.h
// Generated by the protocol buffer compiler. DO NOT EDIT!
#import <ProtocolBuffers/ProtocolBuffers.h>
#class Person;
#class Person_Builder;
#ifndef __has_feature
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif // __has_feature
#ifndef NS_RETURNS_NOT_RETAINED
#if __has_feature(attribute_ns_returns_not_retained)
#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
#else
#define NS_RETURNS_NOT_RETAINED
#endif
#endif
#interface PersonRoot : NSObject {
}
+ (PBExtensionRegistry*) extensionRegistry;
+ (void) registerAllExtensions:(PBMutableExtensionRegistry*) registry;
#end
#interface Person : PBGeneratedMessage {
#private
BOOL hasId_:1;
BOOL hasName_:1;
int32_t id;
NSString* name;
PBAppendableArray * emailArray;
}
- (BOOL) hasId;
- (BOOL) hasName;
#property (readonly) int32_t id;
#property (readonly, strong) NSString* name;
#property (readonly, strong) PBArray * email;
- (NSString*)emailAtIndex:(NSUInteger)index;
+ (Person*) defaultInstance;
- (Person*) defaultInstance;
- (BOOL) isInitialized;
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output;
- (Person_Builder*) builder;
+ (Person_Builder*) builder;
+ (Person_Builder*) builderWithPrototype:(Person*) prototype;
- (Person_Builder*) toBuilder;
+ (Person*) parseFromData:(NSData*) data;
+ (Person*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
+ (Person*) parseFromInputStream:(NSInputStream*) input;
+ (Person*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
+ (Person*) parseFromCodedInputStream:(PBCodedInputStream*) input;
+ (Person*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
#end
#interface Person_Builder : PBGeneratedMessage_Builder {
#private
Person* result;
}
- (Person*) defaultInstance;
- (Person_Builder*) clear;
- (Person_Builder*) clone;
- (Person*) build;
- (Person*) buildPartial;
- (Person_Builder*) mergeFrom:(Person*) other;
- (Person_Builder*) mergeFromCodedInputStream:(PBCodedInputStream*) input;
- (Person_Builder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry;
- (BOOL) hasId;
- (int32_t) id;
- (Person_Builder*) setId:(int32_t) value;
- (Person_Builder*) clearId;
- (BOOL) hasName;
- (NSString*) name;
- (Person_Builder*) setName:(NSString*) value;
- (Person_Builder*) clearName;
- (PBAppendableArray *)email;
- (NSString*)emailAtIndex:(NSUInteger)index;
- (Person_Builder *)addEmail:(NSString*)value;
- (Person_Builder *)setEmailArray:(NSArray *)array;
- (Person_Builder *)setEmailValues:(const NSString* *)values count:(NSUInteger)count;
- (Person_Builder *)clearEmail;
#end
Person.pb.m
// Generated by the protocol buffer compiler. DO NOT EDIT!
#import "Person.pb.h"
#implementation PersonRoot
static PBExtensionRegistry* extensionRegistry = nil;
+ (PBExtensionRegistry*) extensionRegistry {
return extensionRegistry;
}
+ (void) initialize {
if (self == [PersonRoot class]) {
PBMutableExtensionRegistry* registry = [PBMutableExtensionRegistry registry];
[self registerAllExtensions:registry];
extensionRegistry = registry;
}
}
+ (void) registerAllExtensions:(PBMutableExtensionRegistry*) registry {
}
#end
#interface Person ()
#property int32_t id;
#property (strong) NSString* name;
#property (strong) PBAppendableArray * emailArray;
#end
#implementation Person
- (BOOL) hasId {
return !!hasId_;
}
- (void) setHasId:(BOOL) value {
hasId_ = !!value;
}
#synthesize id;
- (BOOL) hasName {
return !!hasName_;
}
- (void) setHasName:(BOOL) value {
hasName_ = !!value;
}
#synthesize name;
#synthesize emailArray;
#dynamic email;
- (id) init {
if ((self = [super init])) {
self.id = 0;
self.name = #"";
}
return self;
}
static Person* defaultPersonInstance = nil;
+ (void) initialize {
if (self == [Person class]) {
defaultPersonInstance = [[Person alloc] init];
}
}
+ (Person*) defaultInstance {
return defaultPersonInstance;
}
- (Person*) defaultInstance {
return defaultPersonInstance;
}
- (NSArray *)email {
return emailArray;
}
- (NSString*)emailAtIndex:(NSUInteger)index {
return [emailArray objectAtIndex:index];
}
- (BOOL) isInitialized {
if (!self.hasId) {
return NO;
}
if (!self.hasName) {
return NO;
}
return YES;
}
- (void) writeToCodedOutputStream:(PBCodedOutputStream*) output {
if (self.hasId) {
[output writeInt32:1 value:self.id];
}
if (self.hasName) {
[output writeString:2 value:self.name];
}
const NSUInteger emailArrayCount = self.emailArray.count;
if (emailArrayCount > 0) {
const NSString* *values = (const NSString* *)self.emailArray.data;
for (NSUInteger i = 0; i < emailArrayCount; ++i) {
[output writeString:3 value:values[i]];
}
}
[self.unknownFields writeToCodedOutputStream:output];
}
- (int32_t) serializedSize {
int32_t size = memoizedSerializedSize;
if (size != -1) {
return size;
}
size = 0;
if (self.hasId) {
size += computeInt32Size(1, self.id);
}
if (self.hasName) {
size += computeStringSize(2, self.name);
}
{
int32_t dataSize = 0;
const NSUInteger count = self.emailArray.count;
const NSString* *values = (const NSString* *)self.emailArray.data;
for (NSUInteger i = 0; i < count; ++i) {
dataSize += computeStringSizeNoTag(values[i]);
}
size += dataSize;
size += 1 * count;
}
size += self.unknownFields.serializedSize;
memoizedSerializedSize = size;
return size;
}
+ (Person*) parseFromData:(NSData*) data {
return (Person*)[[[Person builder] mergeFromData:data] build];
}
+ (Person*) parseFromData:(NSData*) data extensionRegistry:(PBExtensionRegistry*) extensionRegistry {
return (Person*)[[[Person builder] mergeFromData:data extensionRegistry:extensionRegistry] build];
}
+ (Person*) parseFromInputStream:(NSInputStream*) input {
return (Person*)[[[Person builder] mergeFromInputStream:input] build];
}
+ (Person*) parseFromInputStream:(NSInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry {
return (Person*)[[[Person builder] mergeFromInputStream:input extensionRegistry:extensionRegistry] build];
}
+ (Person*) parseFromCodedInputStream:(PBCodedInputStream*) input {
return (Person*)[[[Person builder] mergeFromCodedInputStream:input] build];
}
+ (Person*) parseFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry {
return (Person*)[[[Person builder] mergeFromCodedInputStream:input extensionRegistry:extensionRegistry] build];
}
+ (Person_Builder*) builder {
return [[Person_Builder alloc] init];
}
+ (Person_Builder*) builderWithPrototype:(Person*) prototype {
return [[Person builder] mergeFrom:prototype];
}
- (Person_Builder*) builder {
return [Person builder];
}
- (Person_Builder*) toBuilder {
return [Person builderWithPrototype:self];
}
- (void) writeDescriptionTo:(NSMutableString*) output withIndent:(NSString*) indent {
NSUInteger listCount = 0;
if (self.hasId) {
[output appendFormat:#"%#%#: %#\n", indent, #"id", [NSNumber numberWithInt:self.id]];
}
if (self.hasName) {
[output appendFormat:#"%#%#: %#\n", indent, #"name", self.name];
}
for (NSString* element in self.emailArray) {
[output appendFormat:#"%#%#: %#\n", indent, #"email", element];
}
[self.unknownFields writeDescriptionTo:output withIndent:indent];
}
- (BOOL) isEqual:(id)other {
if (other == self) {
return YES;
}
if (![other isKindOfClass:[Person class]]) {
return NO;
}
Person *otherMessage = other;
return
self.hasId == otherMessage.hasId &&
(!self.hasId || self.id == otherMessage.id) &&
self.hasName == otherMessage.hasName &&
(!self.hasName || [self.name isEqual:otherMessage.name]) &&
[self.emailArray isEqualToArray:otherMessage.emailArray] &&
(self.unknownFields == otherMessage.unknownFields || (self.unknownFields != nil && [self.unknownFields isEqual:otherMessage.unknownFields]));
}
- (NSUInteger) hash {
NSUInteger hashCode = 7;
NSUInteger listCount = 0;
if (self.hasId) {
hashCode = hashCode * 31 + [[NSNumber numberWithInt:self.id] hash];
}
if (self.hasName) {
hashCode = hashCode * 31 + [self.name hash];
}
for (NSString* element in self.emailArray) {
hashCode = hashCode * 31 + [element hash];
}
hashCode = hashCode * 31 + [self.unknownFields hash];
return hashCode;
}
#end
#interface Person_Builder()
#property (strong) Person* result;
#end
#implementation Person_Builder
#synthesize result;
- (id) init {
if ((self = [super init])) {
self.result = [[Person alloc] init];
}
return self;
}
- (PBGeneratedMessage*) internalGetResult {
return result;
}
- (Person_Builder*) clear {
self.result = [[Person alloc] init];
return self;
}
- (Person_Builder*) clone {
return [Person builderWithPrototype:result];
}
- (Person*) defaultInstance {
return [Person defaultInstance];
}
- (Person*) build {
[self checkInitialized];
return [self buildPartial];
}
- (Person*) buildPartial {
Person* returnMe = result;
self.result = nil;
return returnMe;
}
- (Person_Builder*) mergeFrom:(Person*) other {
if (other == [Person defaultInstance]) {
return self;
}
if (other.hasId) {
[self setId:other.id];
}
if (other.hasName) {
[self setName:other.name];
}
if (other.emailArray.count > 0) {
if (result.emailArray == nil) {
result.emailArray = [[NSMutableArray alloc] initWithArray:other.emailArray];
} else {
[result.emailArray addObjectsFromArray:other.emailArray];
}
}
[self mergeUnknownFields:other.unknownFields];
return self;
}
- (Person_Builder*) mergeFromCodedInputStream:(PBCodedInputStream*) input {
return [self mergeFromCodedInputStream:input extensionRegistry:[PBExtensionRegistry emptyRegistry]];
}
- (Person_Builder*) mergeFromCodedInputStream:(PBCodedInputStream*) input extensionRegistry:(PBExtensionRegistry*) extensionRegistry {
PBUnknownFieldSet_Builder* unknownFields = [PBUnknownFieldSet builderWithUnknownFields:self.unknownFields];
while (YES) {
int32_t tag = [input readTag];
switch (tag) {
case 0:
[self setUnknownFields:[unknownFields build]];
return self;
default: {
if (![self parseUnknownField:input unknownFields:unknownFields extensionRegistry:extensionRegistry tag:tag]) {
[self setUnknownFields:[unknownFields build]];
return self;
}
break;
}
case 8: {
[self setId:[input readInt32]];
break;
}
case 18: {
[self setName:[input readString]];
break;
}
case 26: {
[self addEmail:[input readString]];
break;
}
}
}
}
- (BOOL) hasId {
return result.hasId;
}
- (int32_t) id {
return result.id;
}
- (Person_Builder*) setId:(int32_t) value {
result.hasId = YES;
result.id = value;
return self;
}
- (Person_Builder*) clearId {
result.hasId = NO;
result.id = 0;
return self;
}
- (BOOL) hasName {
return result.hasName;
}
- (NSString*) name {
return result.name;
}
- (Person_Builder*) setName:(NSString*) value {
result.hasName = YES;
result.name = value;
return self;
}
- (Person_Builder*) clearName {
result.hasName = NO;
result.name = #"";
return self;
}
- (NSMutableArray *)email {
return result.emailArray;
}
- (NSString*)emailAtIndex:(NSUInteger)index {
return [result emailAtIndex:index];
}
- (Person_Builder *)addEmail:(NSString*)value {
if (result.emailArray == nil) {
result.emailArray = [[NSMutableArray alloc]init];
}
[result.emailArray addObject:value];
return self;
}
- (Person_Builder *)setEmailArray:(NSArray *)array {
result.emailArray = [[NSMutableArray alloc] initWithArray:array];
return self;
}
- (Person_Builder *)clearEmail {
result.emailArray = nil;
return self;
}
#end
Leaving this answer for people who might check this qn later.
It's better to use the C++ protobuf files directly in Xcode. Required fields will not compile at all in the mentioned ios-version of protobuf. Check this answer to add protobuf in your project.