file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
Example/Pods/Nimbus/src/models/src/NIFormCellCatalog.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIFormCellCatalog.h" #import "NITableViewModel+Private.h" #import "NimbusCore.h" #import <objc/message.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif static const CGFloat kSwitchLeftMargin = 10; static const CGFloat kImageViewRightMargin = 10; static const CGFloat kSegmentedControlMargin = 5; static const CGFloat kDatePickerTextFieldRightMargin = 5; @implementation NIFormElement + (id)elementWithID:(NSInteger)elementID { NIFormElement* element = [[self alloc] init]; element.elementID = elementID; return element; } - (Class)cellClass { // You must implement cellClass in your subclass of this object. NIDASSERT(NO); return nil; } @end @implementation NITextInputFormElement + (id)textInputElementWithID:(NSInteger)elementID placeholderText:(NSString *)placeholderText value:(NSString *)value delegate:(id<UITextFieldDelegate>)delegate { NITextInputFormElement* element = [super elementWithID:elementID]; element.placeholderText = placeholderText; element.value = value; element.delegate = delegate; return element; } + (id)textInputElementWithID:(NSInteger)elementID placeholderText:(NSString *)placeholderText value:(NSString *)value { return [self textInputElementWithID:elementID placeholderText:placeholderText value:value delegate:nil]; } + (id)passwordInputElementWithID:(NSInteger)elementID placeholderText:(NSString *)placeholderText value:(NSString *)value delegate:(id<UITextFieldDelegate>)delegate { NITextInputFormElement* element = [self textInputElementWithID:elementID placeholderText:placeholderText value:value delegate:delegate]; element.isPassword = YES; return element; } + (id)passwordInputElementWithID:(NSInteger)elementID placeholderText:(NSString *)placeholderText value:(NSString *)value { return [self passwordInputElementWithID:elementID placeholderText:placeholderText value:value delegate:nil]; } - (Class)cellClass { return [NITextInputFormElementCell class]; } @end @implementation NISwitchFormElement + (id)switchElementWithID:(NSInteger)elementID labelText:(NSString *)labelText value:(BOOL)value didChangeTarget:(id)target didChangeSelector:(SEL)selector { NISwitchFormElement* element = [super elementWithID:elementID]; element.labelText = labelText; element.value = value; element.didChangeTarget = target; element.didChangeSelector = selector; return element; } + (id)switchElementWithID:(NSInteger)elementID labelText:(NSString *)labelText value:(BOOL)value { return [self switchElementWithID:elementID labelText:labelText value:value didChangeTarget:nil didChangeSelector:nil]; } - (Class)cellClass { return [NISwitchFormElementCell class]; } @end @implementation NISliderFormElement + (id)sliderElementWithID:(NSInteger)elementID labelText:(NSString *)labelText value:(float)value minimumValue:(float)minimumValue maximumValue:(float)maximumValue didChangeTarget:(id)target didChangeSelector:(SEL)selector { NISliderFormElement* element = [super elementWithID:elementID]; element.labelText = labelText; element.value = value; element.minimumValue = minimumValue; element.maximumValue = maximumValue; element.didChangeTarget = target; element.didChangeSelector = selector; return element; } + (id)sliderElementWithID:(NSInteger)elementID labelText:(NSString *)labelText value:(float)value minimumValue:(float)minimumValue maximumValue:(float)maximumValue { return [self sliderElementWithID:elementID labelText:labelText value:value minimumValue:minimumValue maximumValue:maximumValue didChangeTarget:nil didChangeSelector:nil]; } - (Class)cellClass { return [NISliderFormElementCell class]; } @end @implementation NISegmentedControlFormElement + (id)segmentedControlElementWithID:(NSInteger)elementID labelText:(NSString *)labelText segments:(NSArray *)segments selectedIndex:(NSInteger)selectedIndex didChangeTarget:(id)target didChangeSelector:(SEL)selector { NISegmentedControlFormElement *element = [super elementWithID:elementID]; element.labelText = labelText; element.selectedIndex = selectedIndex; element.segments = segments; element.didChangeTarget = target; element.didChangeSelector = selector; return element; } + (id)segmentedControlElementWithID:(NSInteger)elementID labelText:(NSString *)labelText segments:(NSArray *)segments selectedIndex:(NSInteger)selectedIndex { return [self segmentedControlElementWithID:elementID labelText:labelText segments:segments selectedIndex:selectedIndex didChangeTarget:nil didChangeSelector:nil]; } - (Class)cellClass { return [NISegmentedControlFormElementCell class]; } @end @implementation NIDatePickerFormElement + (id)datePickerElementWithID:(NSInteger)elementID labelText:(NSString *)labelText date:(NSDate *)date datePickerMode:(UIDatePickerMode)datePickerMode didChangeTarget:(id)target didChangeSelector:(SEL)selector { NIDatePickerFormElement *element = [super elementWithID:elementID]; element.labelText = labelText; element.date = date; element.datePickerMode = datePickerMode; element.didChangeTarget = target; element.didChangeSelector = selector; return element; } + (id)datePickerElementWithID:(NSInteger)elementID labelText:(NSString *)labelText date:(NSDate *)date datePickerMode:(UIDatePickerMode)datePickerMode { return [self datePickerElementWithID:elementID labelText:labelText date:date datePickerMode:datePickerMode didChangeTarget:nil didChangeSelector:nil]; } - (Class)cellClass { return [NIDatePickerFormElementCell class]; } @end #pragma mark - Form Element Cells @implementation NIFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { [self.textLabel setAdjustsFontSizeToFitWidth:YES]; if ([self.textLabel respondsToSelector:@selector(minimumScaleFactor)]) { self.textLabel.minimumScaleFactor = 0.5; } else { #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 [self.textLabel setMinimumFontSize:10.0f]; #endif } } return self; } - (void)prepareForReuse { [super prepareForReuse]; _element = nil; } - (BOOL)shouldUpdateCellWithObject:(id)object { if (_element != object) { _element = object; self.tag = _element.elementID; return YES; } return NO; } @end @implementation NITextInputFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; _textField = [[UITextField alloc] init]; [_textField setTag:self.element.elementID]; [_textField setAdjustsFontSizeToFitWidth:YES]; [_textField setMinimumFontSize:10.0f]; [_textField addTarget:self action:@selector(textFieldDidChangeValue) forControlEvents:UIControlEventAllEditingEvents]; [self.contentView addSubview:_textField]; [self.textLabel removeFromSuperview]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; _textField.frame = UIEdgeInsetsInsetRect(self.contentView.bounds, NICellContentPadding()); } - (void)prepareForReuse { [super prepareForReuse]; _textField.placeholder = nil; _textField.text = nil; } - (BOOL)shouldUpdateCellWithObject:(NITextInputFormElement *)textInputElement { if ([super shouldUpdateCellWithObject:textInputElement]) { _textField.placeholder = textInputElement.placeholderText; _textField.text = textInputElement.value; _textField.delegate = textInputElement.delegate; _textField.secureTextEntry = textInputElement.isPassword; _textField.tag = self.tag; [self setNeedsLayout]; return YES; } return NO; } - (void)textFieldDidChangeValue { NITextInputFormElement* textInputElement = (NITextInputFormElement *)self.element; textInputElement.value = _textField.text; } @end @implementation NISwitchFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; _switchControl = [[UISwitch alloc] init]; [_switchControl addTarget:self action:@selector(switchDidChangeValue) forControlEvents:UIControlEventValueChanged]; [self.contentView addSubview:_switchControl]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; UIEdgeInsets contentPadding = NICellContentPadding(); CGRect contentFrame = UIEdgeInsetsInsetRect(self.contentView.frame, contentPadding); [_switchControl sizeToFit]; CGRect frame = _switchControl.frame; frame.origin.y = NICGFloatFloor((self.contentView.frame.size.height - frame.size.height) / 2); frame.origin.x = self.contentView.frame.size.width - frame.size.width - frame.origin.y; _switchControl.frame = frame; frame = self.textLabel.frame; CGFloat leftEdge = 0; // Take into account the size of the image view. if (nil != self.imageView.image) { leftEdge = self.imageView.frame.size.width + kImageViewRightMargin; } frame.size.width = (self.contentView.frame.size.width - contentFrame.origin.x - _switchControl.frame.size.width - _switchControl.frame.origin.y - kSwitchLeftMargin - leftEdge); self.textLabel.frame = frame; } - (void)prepareForReuse { [super prepareForReuse]; self.textLabel.text = nil; } - (BOOL)shouldUpdateCellWithObject:(NISwitchFormElement *)switchElement { if ([super shouldUpdateCellWithObject:switchElement]) { _switchControl.on = switchElement.value; self.textLabel.text = switchElement.labelText; _switchControl.tag = self.tag; [self setNeedsLayout]; return YES; } return NO; } - (void)switchDidChangeValue { NISwitchFormElement* switchElement = (NISwitchFormElement *)self.element; switchElement.value = _switchControl.on; if (nil != switchElement.didChangeSelector && nil != switchElement.didChangeTarget && [switchElement.didChangeTarget respondsToSelector:switchElement.didChangeSelector]) { // This throws a warning a seclectors that the compiler do not know about cannot be // memory managed by ARC //[switchElement.didChangeTarget performSelector: switchElement.didChangeSelector // withObject: _switchControl]; // The following is a workaround to supress the warning and requires <objc/message.h> objc_msgSend(switchElement.didChangeTarget, switchElement.didChangeSelector, _switchControl); } } @end @implementation NISliderFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; _sliderControl = [[UISlider alloc] init]; [_sliderControl addTarget:self action:@selector(sliderDidChangeValue) forControlEvents:UIControlEventValueChanged]; [self.contentView addSubview:_sliderControl]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; UIEdgeInsets contentPadding = NICellContentPadding(); CGRect contentFrame = UIEdgeInsetsInsetRect(self.contentView.frame, contentPadding); CGFloat labelWidth = contentFrame.size.width * 0.5f; CGRect frame = self.textLabel.frame; frame.size.width = labelWidth; self.textLabel.frame = frame; static const CGFloat kSliderLeftMargin = 8; [_sliderControl sizeToFit]; frame = _sliderControl.frame; frame.origin.y = NICGFloatFloor((self.contentView.frame.size.height - frame.size.height) / 2); frame.origin.x = self.textLabel.frame.origin.x + self.textLabel.frame.size.width + kSliderLeftMargin; frame.size.width = contentFrame.size.width - frame.origin.x; _sliderControl.frame = frame; } - (void)prepareForReuse { [super prepareForReuse]; self.textLabel.text = nil; } - (BOOL)shouldUpdateCellWithObject:(NISliderFormElement *)sliderElement { if ([super shouldUpdateCellWithObject:sliderElement]) { _sliderControl.minimumValue = sliderElement.minimumValue; _sliderControl.maximumValue = sliderElement.maximumValue; _sliderControl.value = sliderElement.value; self.textLabel.text = sliderElement.labelText; _sliderControl.tag = self.tag; [self setNeedsLayout]; return YES; } return NO; } - (void)sliderDidChangeValue { NISliderFormElement* sliderElement = (NISliderFormElement *)self.element; sliderElement.value = _sliderControl.value; if (nil != sliderElement.didChangeSelector && nil != sliderElement.didChangeTarget && [sliderElement.didChangeTarget respondsToSelector:sliderElement.didChangeSelector]) { // This throws a warning a seclectors that the compiler do not know about cannot be // memory managed by ARC //[sliderElement.didChangeTarget performSelector:sliderElement.didChangeSelector // withObject:_sliderControl]; // The following is a workaround to supress the warning and requires <objc/message.h> objc_msgSend(sliderElement.didChangeTarget, sliderElement.didChangeSelector, _sliderControl); } } @end @implementation NISegmentedControlFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; _segmentedControl = [[UISegmentedControl alloc] init]; [_segmentedControl addTarget:self action:@selector(selectedSegmentDidChangeValue) forControlEvents:UIControlEventValueChanged]; [self.contentView addSubview:self.segmentedControl]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; UIEdgeInsets contentPadding = NICellContentPadding(); CGRect contentFrame = UIEdgeInsetsInsetRect(self.contentView.frame, contentPadding); [_segmentedControl sizeToFit]; CGRect frame = _segmentedControl.frame; frame.size.height = self.contentView.frame.size.height - (2 * kSegmentedControlMargin); frame.origin.y = NICGFloatFloor((self.contentView.frame.size.height - frame.size.height) / 2); frame.origin.x = CGRectGetMaxX(contentFrame) - frame.size.width - kSegmentedControlMargin; _segmentedControl.frame = frame; frame = self.textLabel.frame; CGFloat leftEdge = 0; // Take into account the size of the image view. if (nil != self.imageView.image) { leftEdge = self.imageView.frame.size.width + kImageViewRightMargin; } frame.size.width = (self.contentView.frame.size.width - contentFrame.origin.x - _segmentedControl.frame.size.width - kSegmentedControlMargin - kSwitchLeftMargin - leftEdge); self.textLabel.frame = frame; } - (void)prepareForReuse { [super prepareForReuse]; self.textLabel.text = nil; [self.segmentedControl removeAllSegments]; } - (BOOL)shouldUpdateCellWithObject:(NISegmentedControlFormElement *)segmentedControlElement { if ([super shouldUpdateCellWithObject:segmentedControlElement]) { self.textLabel.text = segmentedControlElement.labelText; [segmentedControlElement.segments enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj isKindOfClass:[NSString class]]) { [_segmentedControl insertSegmentWithTitle:obj atIndex:idx animated:NO]; } else if ([obj isKindOfClass:[UIImage class]]) { [_segmentedControl insertSegmentWithImage:obj atIndex:idx animated:NO]; } }]; _segmentedControl.tag = self.tag; _segmentedControl.selectedSegmentIndex = segmentedControlElement.selectedIndex; [self setNeedsLayout]; return YES; } return NO; } - (void)selectedSegmentDidChangeValue { NISegmentedControlFormElement *segmentedControlElement = (NISegmentedControlFormElement *)self.element; segmentedControlElement.selectedIndex = self.segmentedControl.selectedSegmentIndex; if (nil != segmentedControlElement.didChangeSelector && nil != segmentedControlElement.didChangeTarget && [segmentedControlElement.didChangeTarget respondsToSelector:segmentedControlElement.didChangeSelector]) { // [segmentedControlElement.didChangeTarget performSelector:segmentedControlElement.didChangeSelector // withObject:_segmentedControl]; // The following is a workaround to supress the warning and requires <objc/message.h> objc_msgSend(segmentedControlElement.didChangeTarget, segmentedControlElement.didChangeSelector, _segmentedControl); } } @end @interface NIDatePickerFormElementCell() @property (nonatomic, strong) UITextField* dumbDateField; @end @implementation NIDatePickerFormElementCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; _datePicker = [[UIDatePicker alloc] init]; [_datePicker addTarget:self action:@selector(selectedDateDidChange) forControlEvents:UIControlEventValueChanged]; _dateField = [[UITextField alloc] init]; _dateField.delegate = self; _dateField.font = [UIFont systemFontOfSize:16.0f]; _dateField.minimumFontSize = 10.0f; _dateField.backgroundColor = [UIColor clearColor]; _dateField.adjustsFontSizeToFitWidth = YES; #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 _dateField.textAlignment = UITextAlignmentRight; #else _dateField.textAlignment = NSTextAlignmentRight; #endif _dateField.inputView = _datePicker; [self.contentView addSubview:_dateField]; _dumbDateField = [[UITextField alloc] init]; _dumbDateField.hidden = YES; _dumbDateField.enabled = NO; [self.contentView addSubview:_dumbDateField]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; UIEdgeInsets contentPadding = NICellContentPadding(); CGRect contentFrame = UIEdgeInsetsInsetRect(self.contentView.frame, contentPadding); [_dateField sizeToFit]; CGRect frame = _dateField.frame; frame.origin.y = NICGFloatFloor((self.contentView.frame.size.height - frame.size.height) / 2); frame.origin.x = self.contentView.frame.size.width - frame.size.width - kDatePickerTextFieldRightMargin; _dateField.frame = frame; self.dumbDateField.frame = _dateField.frame; frame = self.textLabel.frame; CGFloat leftEdge = 0; // Take into account the size of the image view. if (nil != self.imageView.image) { leftEdge = self.imageView.frame.size.width + kImageViewRightMargin; } frame.size.width = (self.contentView.frame.size.width - contentFrame.origin.x - _dateField.frame.size.width - _dateField.frame.origin.y - leftEdge); self.textLabel.frame = frame; } - (void)prepareForReuse { [super prepareForReuse]; self.textLabel.text = nil; _dateField.text = nil; } - (BOOL)shouldUpdateCellWithObject:(NIDatePickerFormElement *)datePickerElement { if ([super shouldUpdateCellWithObject:datePickerElement]) { self.textLabel.text = datePickerElement.labelText; self.datePicker.datePickerMode = datePickerElement.datePickerMode; self.datePicker.date = datePickerElement.date; switch (self.datePicker.datePickerMode) { case UIDatePickerModeDate: self.dateField.text = [NSDateFormatter localizedStringFromDate:self.datePicker.date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle]; break; case UIDatePickerModeTime: self.dateField.text = [NSDateFormatter localizedStringFromDate:self.datePicker.date dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle]; break; case UIDatePickerModeCountDownTimer: if (self.datePicker.countDownDuration == 0) { self.dateField.text = NSLocalizedString(@"0 minutes", @"0 minutes"); } else { int hours = (int)(self.datePicker.countDownDuration / 3600); int minutes = (int)((self.datePicker.countDownDuration - hours * 3600) / 60); self.dateField.text = [NSString stringWithFormat: NSLocalizedString(@"%d hours, %d min", @"datepicker countdown hours and minutes"), hours, minutes]; } break; case UIDatePickerModeDateAndTime: default: self.dateField.text = [NSDateFormatter localizedStringFromDate:self.datePicker.date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]; break; } self.dumbDateField.text = self.dateField.text; _dateField.tag = self.tag; _datePicker.date = datePickerElement.date; _datePicker.tag = self.tag; [self setNeedsLayout]; return YES; } return NO; } - (void)selectedDateDidChange { switch (self.datePicker.datePickerMode) { case UIDatePickerModeDate: self.dateField.text = [NSDateFormatter localizedStringFromDate:_datePicker.date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle]; break; case UIDatePickerModeTime: self.dateField.text = [NSDateFormatter localizedStringFromDate:_datePicker.date dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle]; break; case UIDatePickerModeCountDownTimer: if (self.datePicker.countDownDuration == 0) { self.dateField.text = NSLocalizedString(@"0 minutes", @"0 minutes"); } else { int hours = (int)(self.datePicker.countDownDuration / 3600); int minutes = (int)((self.datePicker.countDownDuration - hours * 3600) / 60); self.dateField.text = [NSString stringWithFormat: NSLocalizedString(@"%d hours, %d min", @"datepicker countdown hours and minutes"), hours, minutes]; } break; case UIDatePickerModeDateAndTime: default: self.dateField.text = [NSDateFormatter localizedStringFromDate:_datePicker.date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle]; break; } self.dumbDateField.text = self.dateField.text; NIDatePickerFormElement *datePickerElement = (NIDatePickerFormElement *)self.element; datePickerElement.date = _datePicker.date; if (nil != datePickerElement.didChangeSelector && nil != datePickerElement.didChangeTarget && [datePickerElement.didChangeTarget respondsToSelector:datePickerElement.didChangeSelector]) { // [datePickerElement.didChangeTarget performSelector:datePickerElement.didChangeSelector withObject:self.datePicker]; // The following is a workaround to supress the warning and requires <objc/message.h> objc_msgSend(datePickerElement.didChangeTarget, datePickerElement.didChangeSelector, _datePicker); } } - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { self.dumbDateField.delegate = self.dateField.delegate; self.dumbDateField.font = self.dateField.font; self.dumbDateField.minimumFontSize = self.dateField.minimumFontSize; self.dumbDateField.backgroundColor = self.dateField.backgroundColor; self.dumbDateField.adjustsFontSizeToFitWidth = self.dateField.adjustsFontSizeToFitWidth; self.dumbDateField.textAlignment = self.dateField.textAlignment; self.dumbDateField.textColor = self.dateField.textColor; textField.hidden = YES; self.dumbDateField.hidden = NO; return YES; } - (void)textFieldDidEndEditing:(UITextField *)textField { textField.hidden = NO; self.dumbDateField.hidden = YES; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { return NO; } @end @implementation NITableViewModel (NIFormElementSearch) - (id)elementWithID:(NSInteger)elementID { for (NITableViewModelSection* section in self.sections) { for (NIFormElement* element in section.rows) { if (![element isKindOfClass:[NIFormElement class]]) { continue; } if (element.elementID == elementID) { return element; } } } return nil; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIMutableTableViewModel+Private.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIMutableTableViewModel.h" @interface NIMutableTableViewModel (Private) @property (nonatomic, strong) NSMutableArray* sections; // Array of NITableViewModelSection @property (nonatomic, strong) NSMutableArray* sectionIndexTitles; @property (nonatomic, strong) NSMutableDictionary* sectionPrefixToSectionIndex; @end @interface NITableViewModelSection (Mutable) - (NSMutableArray *)mutableRows; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIMutableTableViewModel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NITableViewModel.h" @class NIMutableTableViewModel; /** * A protocol for NIMutableTableViewModel to handle editing states for objects. * * @ingroup TableViewModels */ @protocol NIMutableTableViewModelDelegate <NSObject, NITableViewModelDelegate> @optional /** * Asks the receiver whether the object at the given index path should be editable. * * If this method is not implemented, the default response is assumed to be NO. */ - (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel canEditObject:(id)object atIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView; /** * Asks the receiver whether the object at the given index path should be moveable. * * If this method is not implemented, the default response is assumed to be NO. */ - (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel canMoveObject:(id)object atIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView; /** * Asks the receiver whether the given object should be moved. * * If this method is not implemented, the default response is assumed to be YES. * * Returning NO will stop the model from handling the move logic. */ - (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel shouldMoveObject:(id)object atIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)toIndexPath inTableView:(UITableView *)tableView; /** * Asks the receiver what animation should be used when deleting the object at the given index path. * * If this method is not implemented, the default response is assumed to be * UITableViewRowAnimationAutomatic. */ - (UITableViewRowAnimation)tableViewModel:(NIMutableTableViewModel *)tableViewModel deleteRowAnimationForObject:(id)object atIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView; /** * Asks the receiver whether the given object should be deleted. * * If this method is not implemented, the default response is assumed to be YES. * * Returning NO will stop the model from handling the deletion logic. This is a good opportunity for * you to show a UIAlertView or similar feedback prompt to the user before initiating the deletion * yourself. * * If you implement the deletion of the object yourself, your code may resemble the following: @code NSArray *indexPaths = [self removeObjectAtIndexPath:indexPath]; [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic]; @endcode */ - (BOOL)tableViewModel:(NIMutableTableViewModel *)tableViewModel shouldDeleteObject:(id)object atIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView; @end /** * The NIMutableTableViewModel class is a mutable table view model. * * When modifications are made to the model there are two ways to reflect the changes in the table * view. * * - Call reloadData on the table view. This is the most destructive way to update the table view. * - Call insert/delete/reload methods on the table view with the retuned index path arrays. * * The latter option is the recommended approach to adding new cells to a table view. Each method in * the mutable table view model returns a data structure that can be used to inform the table view * of the exact modifications that have been made to the model. * * Example of adding a new section: @code // Appends a new section to the end of the model. NSIndexSet* indexSet = [self.model addSectionWithTitle:@"New section"]; // Appends a cell to the last section in the model (in this case, the new section we just created). [self.model addObject:[NITitleCellObject objectWithTitle:@"A cell"]]; // Inform the table view that we've modified the model. [self.tableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic]; @endcode * * @ingroup TableViewModels */ @interface NIMutableTableViewModel : NITableViewModel - (NSArray *)addObject:(id)object; - (NSArray *)addObject:(id)object toSection:(NSUInteger)section; - (NSArray *)addObjectsFromArray:(NSArray *)array; - (NSArray *)insertObject:(id)object atRow:(NSUInteger)row inSection:(NSUInteger)section; - (NSArray *)removeObjectAtIndexPath:(NSIndexPath *)indexPath; - (NSIndexSet *)addSectionWithTitle:(NSString *)title; - (NSIndexSet *)insertSectionWithTitle:(NSString *)title atIndex:(NSUInteger)index; - (NSIndexSet *)removeSectionAtIndex:(NSUInteger)index; - (void)updateSectionIndex; @property (nonatomic, weak) id<NIMutableTableViewModelDelegate> delegate; @end /** @name Modifying Objects */ /** * Appends an object to the last section. * * If no sections exist, a section will be created without a title and the object will be added to * this new section. * * @param object The object to append to the last section. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableTableViewModel::addObject: */ /** * Appends an object to the end of the given section. * * @param object The object to append to the section. * @param section The index of the section to which this object should be appended. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableTableViewModel::addObject:toSection: */ /** * Appends an array of objects to the last section. * * If no section exists, a section will be created without a title and the objects will be added to * this new section. * * @param array The array of objects to append to the last section. * @returns An array of NSIndexPath objects representing the index paths of the objects in the * model. * @fn NIMutableTableViewModel::addObjectsFromArray: */ /** * Inserts an object into the given section at the given row. * * @param object The object to append to the section. * @param row The row within the section at which to insert the object. * @param section The index of the section in which the object should be inserted. * @returns An array with a single NSIndexPath representing the index path of the new object * in the model. * @fn NIMutableTableViewModel::insertObject:atRow:inSection: */ /** * Removes an object at the given index path. * * If the index path does not represent a valid object then a debug assertion will fire and the * method will return nil without removing any object. * * @param indexPath The index path at which to remove a single object. * @returns An array with a single NSIndexPath representing the index path of the object that * was removed from the model, or nil if no object exists at the given index path. * @fn NIMutableTableViewModel::removeObjectAtIndexPath: */ /** @name Modifying Sections */ /** * Appends a section with a given title to the model. * * @param title The title of the new section. * @returns An index set with a single index representing the index of the new section. * @fn NIMutableTableViewModel::addSectionWithTitle: */ /** * Inserts a section with a given title to the model at the given index. * * @param title The title of the new section. * @param index The index in the model at which to add the new section. * @returns An index set with a single index representing the index of the new section. * @fn NIMutableTableViewModel::insertSectionWithTitle:atIndex: */ /** * Removes a section at the given index. * * @param index The index in the model of the section to remove. * @returns An index set with a single index representing the index of the removed section. * @fn NIMutableTableViewModel::removeSectionAtIndex: */ /** @name Updating the Section Index */ /** * Updates the section index with the current section index settings. * * This method should be called after modifying the model if a section index is being used. * * @fn NIMutableTableViewModel::updateSectionIndex */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIMutableTableViewModel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIMutableTableViewModel.h" #import "NITableViewModel+Private.h" #import "NIMutableTableViewModel+Private.h" #import "NimbusCore.h" @implementation NIMutableTableViewModel #pragma mark - Public - (NSArray *)addObject:(id)object { NITableViewModelSection* section = self.sections.count == 0 ? [self _appendSection] : self.sections.lastObject; [section.mutableRows addObject:object]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:section.mutableRows.count - 1 inSection:self.sections.count - 1]]; } - (NSArray *)addObject:(id)object toSection:(NSUInteger)sectionIndex { NIDASSERT(sectionIndex >= 0 && sectionIndex < self.sections.count); NITableViewModelSection *section = [self.sections objectAtIndex:sectionIndex]; [section.mutableRows addObject:object]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:section.mutableRows.count - 1 inSection:sectionIndex]]; } - (NSArray *)addObjectsFromArray:(NSArray *)array { NSMutableArray* indices = [NSMutableArray array]; for (id object in array) { [indices addObject:[[self addObject:object] objectAtIndex:0]]; } return indices; } - (NSArray *)insertObject:(id)object atRow:(NSUInteger)row inSection:(NSUInteger)sectionIndex { NIDASSERT(sectionIndex >= 0 && sectionIndex < self.sections.count); NITableViewModelSection *section = [self.sections objectAtIndex:sectionIndex]; [section.mutableRows insertObject:object atIndex:row]; return [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:sectionIndex]]; } - (NSArray *)removeObjectAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT(indexPath.section < (NSInteger)self.sections.count); if (indexPath.section >= (NSInteger)self.sections.count) { return nil; } NITableViewModelSection* section = [self.sections objectAtIndex:indexPath.section]; NIDASSERT(indexPath.row < (NSInteger)section.mutableRows.count); if (indexPath.row >= (NSInteger)section.mutableRows.count) { return nil; } [section.mutableRows removeObjectAtIndex:indexPath.row]; return [NSArray arrayWithObject:indexPath]; } - (NSIndexSet *)addSectionWithTitle:(NSString *)title { NITableViewModelSection* section = [self _appendSection]; section.headerTitle = title; return [NSIndexSet indexSetWithIndex:self.sections.count - 1]; } - (NSIndexSet *)insertSectionWithTitle:(NSString *)title atIndex:(NSUInteger)index { NITableViewModelSection* section = [self _insertSectionAtIndex:index]; section.headerTitle = title; return [NSIndexSet indexSetWithIndex:index]; } - (NSIndexSet *)removeSectionAtIndex:(NSUInteger)index { NIDASSERT(index >= 0 && index < self.sections.count); [self.sections removeObjectAtIndex:index]; return [NSIndexSet indexSetWithIndex:index]; } - (void)updateSectionIndex { [self _compileSectionIndex]; } #pragma mark - Private - (NITableViewModelSection *)_appendSection { if (nil == self.sections) { self.sections = [NSMutableArray array]; } NITableViewModelSection* section = nil; section = [[NITableViewModelSection alloc] init]; section.rows = [NSMutableArray array]; [self.sections addObject:section]; return section; } - (NITableViewModelSection *)_insertSectionAtIndex:(NSUInteger)index { if (nil == self.sections) { self.sections = [NSMutableArray array]; } NITableViewModelSection* section = nil; section = [[NITableViewModelSection alloc] init]; section.rows = [NSMutableArray array]; NIDASSERT(index >= 0 && index <= self.sections.count); [self.sections insertObject:section atIndex:index]; return section; } #pragma mark - UITableViewDataSource - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { if ([self.delegate respondsToSelector:@selector(tableViewModel:canEditObject:atIndexPath:inTableView:)]) { id object = [self objectAtIndexPath:indexPath]; return [self.delegate tableViewModel:self canEditObject:object atIndexPath:indexPath inTableView:tableView]; } else { return NO; } } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { id object = [self objectAtIndexPath:indexPath]; if (editingStyle == UITableViewCellEditingStyleDelete) { BOOL shouldDelete = YES; if ([self.delegate respondsToSelector:@selector(tableViewModel:shouldDeleteObject:atIndexPath:inTableView:)]) { shouldDelete = [self.delegate tableViewModel:self shouldDeleteObject:object atIndexPath:indexPath inTableView:tableView]; } if (shouldDelete) { NSArray *indexPaths = [self removeObjectAtIndexPath:indexPath]; UITableViewRowAnimation animation = UITableViewRowAnimationAutomatic; if ([self.delegate respondsToSelector:@selector(tableViewModel:deleteRowAnimationForObject:atIndexPath:inTableView:)]) { animation = [self.delegate tableViewModel:self deleteRowAnimationForObject:object atIndexPath:indexPath inTableView:tableView]; } [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:animation]; } } } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { if ([self.delegate respondsToSelector:@selector(tableViewModel:canMoveObject:atIndexPath:inTableView:)]) { id object = [self objectAtIndexPath:indexPath]; return [self.delegate tableViewModel:self canMoveObject:object atIndexPath:indexPath inTableView:tableView]; } else { return NO; } } - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath { id object = [self objectAtIndexPath:sourceIndexPath]; BOOL shouldMove = YES; if ([self.delegate respondsToSelector:@selector(tableViewModel:shouldMoveObject:atIndexPath:toIndexPath:inTableView:)]) { shouldMove = [self.delegate tableViewModel:self shouldMoveObject:object atIndexPath:sourceIndexPath toIndexPath:destinationIndexPath inTableView:tableView]; } if (shouldMove) { [self removeObjectAtIndexPath:sourceIndexPath]; [self insertObject:object atRow:destinationIndexPath.row inSection:destinationIndexPath.section]; } } @end @implementation NITableViewModelSection (Mutable) - (NSMutableArray *)mutableRows { NIDASSERT([self.rows isKindOfClass:[NSMutableArray class]] || nil == self.rows); self.rows = nil == self.rows ? [NSMutableArray array] : self.rows; return (NSMutableArray *)self.rows; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIRadioGroup.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NICellFactory.h" @protocol NIRadioGroupDelegate; @class NIRadioGroupController; /** * A general-purpose radio group. * * This group object manages radio-style selection of objects. Only one object may be selected at * a time. * * Due to the general-purpose nature of this object, it can be used with UITableViews or any other * view that has sets of objects being displayed. This object can insert itself into a * UITableViewDelegate call chain to minimize the amount of code that needs to be written in your * controller. * * If you add a NIRadioGroup object to a NITableViewModel, it will show a cell that displays the * current radio group selection. This cell is also tappable. Tapping this cell will push a * controller onto the navigation stack that presents the radio group options for the user to * select. The radio group delegate is notified immediately when a selection is made and the * tapped cell is also updated to reflect the new selection. * * @ingroup ModelTools */ @interface NIRadioGroup : NSObject <NICellObject, UITableViewDelegate> // Designated initializer. - (id)initWithController:(UIViewController *)controller; @property (nonatomic, weak) id<NIRadioGroupDelegate> delegate; #pragma mark Mapping Objects - (id)mapObject:(id)object toIdentifier:(NSInteger)identifier; #pragma mark Selection - (BOOL)hasSelection; @property (nonatomic, assign) NSInteger selectedIdentifier; - (void)clearSelection; #pragma mark Object State - (BOOL)isObjectInRadioGroup:(id)object; - (BOOL)isObjectSelected:(id)object; - (NSInteger)identifierForObject:(id)object; #pragma mark Forwarding @property (nonatomic, assign) UITableViewCellSelectionStyle tableViewCellSelectionStyle; - (id<UITableViewDelegate>)forwardingTo:(id<UITableViewDelegate>)forwardDelegate; - (void)removeForwarding:(id<UITableViewDelegate>)forwardDelegate; #pragma mark Sub Radio Groups @property (nonatomic, copy) NSString* cellTitle; @property (nonatomic, copy) NSString* controllerTitle; - (NSArray *)allObjects; @end /** * The delegate for NIRadioGroup. * * @ingroup ModelTools */ @protocol NIRadioGroupDelegate <NSObject> @required /** * Called when the user changes the radio group selection. * * @param radioGroup The radio group object. * @param identifier The newly selected identifier. */ - (void)radioGroup:(NIRadioGroup *)radioGroup didSelectIdentifier:(NSInteger)identifier; @optional /** * Fetches the text that will be displayed in a radio group cell for the current selection. * * This is only used when the radio group is added to a table view as a sub radio group. */ - (NSString *)radioGroup:(NIRadioGroup *)radioGroup textForIdentifier:(NSInteger)identifier; /** * The radio group controller is about to appear. * * This method provides a customization point for the radio group view controller. * * @return YES if controller should be pushed onto the current navigation stack. * NO if you are going to present the controller yourself. */ - (BOOL)radioGroup:(NIRadioGroup *)radioGroup radioGroupController:(NIRadioGroupController *)radioGroupController willAppear:(BOOL)animated; @end /** * The cell that is displayed for a NIRadioGroup object when it is displayed in a UITableView. * * This class is exposed publicly so that you may subclass it and customize the way it displays * its information. You can override the cell class that the radio group uses in two ways: * * 1. Subclass NIRadioGroup and return a different cell class in -cellClass. * 2. Create a NICellFactory and map NIRadioGroup to a different cell class and then use this * factory for your model in your table view controller. * * By default this cell displays the cellTitle property of the radio group on the left and the * text retrieved from the radio group delegate's radioGroup:textForIdentifier: method on the right. */ @interface NIRadioGroupCell : UITableViewCell <NICell> @end /** @name Creating Radio Groups */ /** * Initializes a newly allocated radio group object with the given controller. * * This is the designated initializer. * * The given controller is stored as a weak reference internally. * * @param controller The controller that will be used when this object is used as a sub radio * group. * @fn NIRadioGroup::initWithController: */ /** @name Mapping Objects */ /** * Maps the given object to the given identifier. * * The identifier will be used in all subsequent operations and is a means of abstracting away * the objects. The identifier range does not have to be sequential. The only reserved value is * NSIntegerMin, which is used to signify that no selection exists. * * You can NOT map the same object to multiple identifiers. Attempts to do so fill fire a debug * assertion and will not map the new object in the radio group. * * @param object The object to map to the identifier. * @param identifier The identifier that will represent the object. * @returns The object that was mapped. * @fn NIRadioGroup::mapObject:toIdentifier: */ /** @name Selection */ /** * Whether or not a selection has been made. * * @fn NIRadioGroup::hasSelection */ /** * The currently selected identifier if one is selected, otherwise returns NSIntegerMin. * * @fn NIRadioGroup::selectedIdentifier */ /** * Removes the selection from this cell group. * * @fn NIRadioGroup::clearSelection */ /** @name Object State */ /** * Returns YES if the given object is in this radio group. * * @fn NIRadioGroup::isObjectInRadioGroup: */ /** * Returns YES if the given object is selected. * * This method should only be called after verifying that the object is contained within the radio * group with isObjectInRadioGroup:. * * @fn NIRadioGroup::isObjectSelected: */ /** * Returns the mapped identifier for this object. * * This method should only be called after verifying that the object is contained within the radio * group with isObjectInRadioGroup:. * * @fn NIRadioGroup::identifierForObject: */ /** @name Forwarding */ /** * The cell selection style that will be applied to the cell when it is displayed using * delegate forwarding. * * By default this is UITableViewCellSelectionStyleBlue. * * @fn NIRadioGroup::tableViewCellSelectionStyle */ /** * Sets the delegate that table view methods should be forwarded to. * * This method allows you to insert the radio group into the call chain for the table view's * delegate methods. * * Example: * @code // Let the radio group handle delegate methods and then forward them to whatever delegate was // already assigned. self.tableView.delegate = [self.radioGroup forwardingTo:self.tableView.delegate]; @endcode * * @param forwardDelegate The delegate to forward invocations to. * @returns self so that this method can be chained. * @fn NIRadioGroup::forwardingTo: */ /** * Removes the delegate from the forwarding chain. * * If a forwared delegate is about to be released but this object may live on, you must remove the * forwarding in order to avoid invalid access errors at runtime. * * @param forwardDelegate The delegate to stop forwarding invocations to. * @fn NIRadioGroup::removeForwarding: */ /** * The title of the cell that is displayed for a radio group in a UITableView. * * @fn NIRadioGroup::cellTitle */ /** * The title of the controller that shows the sub radio group selection. * * @fn NIRadioGroup::controllerTitle */ /** * An array of mapped objects in this radio group, ordered in the same order they were mapped. * * This is used primarily by NIRadioGroupController to display the radio group options. * * @fn NIRadioGroup::allObjects */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIRadioGroup.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIRadioGroup.h" #import "NIRadioGroupController.h" #import "NITableViewModel.h" #import "NimbusCore.h" #import <objc/runtime.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif static const NSInteger kInvalidSelection = NSIntegerMin; @interface NIRadioGroup() @property (nonatomic, readonly, weak) UIViewController* controller; @property (nonatomic, readonly, strong) NSMutableDictionary* objectMap; @property (nonatomic, readonly, strong) NSMutableSet* objectSet; @property (nonatomic, readonly, strong) NSMutableArray* objectOrder; @property (nonatomic, assign) BOOL hasSelection; @property (nonatomic, readonly, strong) NSMutableSet* forwardDelegates; @end @implementation NIRadioGroup @synthesize selectedIdentifier = _selectedIdentifier; - (id)initWithController:(UIViewController *)controller { if ((self = [super init])) { _controller = controller; _objectMap = [[NSMutableDictionary alloc] init]; _objectSet = [[NSMutableSet alloc] init]; _objectOrder = [[NSMutableArray alloc] init]; _forwardDelegates = NICreateNonRetainingMutableSet(); _tableViewCellSelectionStyle = UITableViewCellSelectionStyleBlue; } return self; } - (id)init { return [self initWithController:nil]; } #pragma mark - Private - (id)keyForIdentifier:(NSInteger)identifier { return [NSNumber numberWithInteger:identifier]; } #pragma mark - NICellObject - (Class)cellClass { return [NIRadioGroupCell class]; } - (UITableViewCellStyle)cellStyle { return UITableViewCellStyleValue1; } #pragma mark - Forward Invocations - (BOOL)shouldForwardSelector:(SEL)selector { struct objc_method_description description; description = protocol_getMethodDescription(@protocol(UITableViewDelegate), selector, NO, YES); return (description.name != NULL && description.types != NULL); } - (BOOL)respondsToSelector:(SEL)selector { if ([super respondsToSelector:selector]) { return YES; } else if ([self shouldForwardSelector:selector]) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:selector]) { return YES; } } } return NO; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { NSMethodSignature *signature = [super methodSignatureForSelector:selector]; if (signature == nil) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:selector]) { signature = [delegate methodSignatureForSelector:selector]; } } } return signature; } - (void)forwardInvocation:(NSInvocation *)invocation { BOOL didForward = NO; if ([self shouldForwardSelector:invocation.selector]) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:invocation.selector]) { [invocation invokeWithTarget:delegate]; didForward = YES; break; } } } if (!didForward) { [super forwardInvocation:invocation]; } } - (id<UITableViewDelegate>)forwardingTo:(id<UITableViewDelegate>)forwardDelegate { [self.forwardDelegates addObject:forwardDelegate]; return self; } - (void)removeForwarding:(id<UITableViewDelegate>)forwardDelegate { [self.forwardDelegates removeObject:forwardDelegate]; } #pragma mark - Public - (id)mapObject:(id)object toIdentifier:(NSInteger)identifier { NIDASSERT(nil != object); NIDASSERT(identifier != kInvalidSelection); NIDASSERT(![self isObjectInRadioGroup:object]); if (nil == object) { return nil; } if (kInvalidSelection == identifier) { return nil; } if ([self isObjectInRadioGroup:object]) { return nil; } [self.objectMap setObject:object forKey:[self keyForIdentifier:identifier]]; [self.objectSet addObject:object]; [self.objectOrder addObject:object]; return object; } - (void)setSelectedIdentifier:(NSInteger)selectedIdentifier { id key = [self keyForIdentifier:selectedIdentifier]; NIDASSERT(nil != [self.objectMap objectForKey:key]); if (nil != [self.objectMap objectForKey:key]) { _selectedIdentifier = selectedIdentifier; self.hasSelection = YES; } else { // If we set an invalid identifier then clear the current selection. self.hasSelection = NO; } } - (NSInteger)selectedIdentifier { return self.hasSelection ? _selectedIdentifier : kInvalidSelection; } - (void)clearSelection { self.hasSelection = NO; } - (BOOL)isObjectInRadioGroup:(id)object { if (nil == object) { return NO; } return [self.objectSet containsObject:object]; } - (BOOL)isObjectSelected:(id)object { if (nil == object) { return NO; } NIDASSERT(nil != object); NIDASSERT([self isObjectInRadioGroup:object]); NSArray* keys = [self.objectMap allKeysForObject:object]; NSInteger selectedIdentifier = self.selectedIdentifier; for (NSNumber* key in keys) { if ([key intValue] == selectedIdentifier) { return YES; } } return NO; } - (NSInteger)identifierForObject:(id)object { if (nil == object) { return NO; } NIDASSERT(nil != object); NIDASSERT([self isObjectInRadioGroup:object]); NSArray* keys = [self.objectMap allKeysForObject:object]; return keys.count > 0 ? [[keys objectAtIndex:0] intValue] : kInvalidSelection; } - (NSArray *)allObjects { return [self.objectOrder copy]; } #pragma mark - UITableViewDelegate - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]); if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) { NITableViewModel* model = (NITableViewModel *)tableView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectInRadioGroup:object]) { cell.accessoryType = ([self isObjectSelected:object] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone); cell.selectionStyle = self.tableViewCellSelectionStyle; } } // Forward the invocation along. for (id<UITableViewDelegate> delegate in self.forwardDelegates) { if ([delegate respondsToSelector:_cmd]) { [delegate tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath]; } } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]); if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) { NITableViewModel* model = (NITableViewModel *)tableView.dataSource; id object = [model objectAtIndexPath:indexPath]; if (object == self) { // You must provide a controller in the initWithController: initializer. NIDASSERT(nil != self.controller); NIRadioGroupController* controller = [[NIRadioGroupController alloc] initWithRadioGroup:self tappedCell:(id<NICell>)[tableView cellForRowAtIndexPath:indexPath]]; controller.title = self.controllerTitle; BOOL shouldPush = YES; // Notify the delegate that the controller is about to appear. if ([self.delegate respondsToSelector:@selector(radioGroup:radioGroupController:willAppear:)]) { shouldPush = [self.delegate radioGroup:self radioGroupController:controller willAppear:YES]; } if (shouldPush) { [self.controller.navigationController pushViewController:controller animated:YES]; } } else if ([self isObjectInRadioGroup:object]) { NSInteger newSelection = [self identifierForObject:object]; if (newSelection != self.selectedIdentifier) { [self setSelectedIdentifier:newSelection]; // It's easiest to simply reload the visible table cells. Reloading only the radio group // cells would require iterating through the visible cell objects and determining whether // each was in the radio group. This is more complex behavior that should be relegated to // the controller. [tableView reloadRowsAtIndexPaths:tableView.indexPathsForVisibleRows withRowAnimation:UITableViewRowAnimationNone]; // After we reload the table view the selection will be lost, so set the selection again. [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; [self.delegate radioGroup:self didSelectIdentifier:newSelection]; } // Fade the selection out. [tableView deselectRowAtIndexPath:indexPath animated:YES]; } } // Forward the invocation along. for (id<UITableViewDelegate> delegate in self.forwardDelegates) { if ([delegate respondsToSelector:_cmd]) { [delegate tableView:tableView didSelectRowAtIndexPath:indexPath]; } } } @end @implementation NIRadioGroupCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } return self; } - (void)prepareForReuse { [super prepareForReuse]; self.textLabel.text = nil; self.detailTextLabel.text = nil; } - (BOOL)shouldUpdateCellWithObject:(NIRadioGroup *)radioGroup { self.selectionStyle = radioGroup.tableViewCellSelectionStyle; // You should provide a cell title for the radio group. NIDASSERT(NIIsStringWithAnyText(radioGroup.cellTitle)); self.textLabel.text = radioGroup.cellTitle; if ([radioGroup.delegate respondsToSelector:@selector(radioGroup:textForIdentifier:)]) { self.detailTextLabel.text = [radioGroup.delegate radioGroup:radioGroup textForIdentifier:radioGroup.selectedIdentifier]; } return YES; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIRadioGroupController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> @class NIRadioGroup; @protocol NICell; /** * A controller that displays the set of options in a radio group. * * This controller is instantiated and pushed onto the navigation stack when the user taps a radio * group cell. * * @ingroup ModelTools */ @interface NIRadioGroupController : UITableViewController // Designated initializer. - (id)initWithRadioGroup:(NIRadioGroup *)radioGroup tappedCell:(id<NICell>)tappedCell; @end /** * Initializes a newly allocated radio group controller with the given radio group and cell. * * The radio group and cell are strongly referenced for the lifetime of this controller. * * @fn NIRadioGroupController::initWithRadioGroup:tappedCell: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NIRadioGroupController.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIRadioGroupController.h" #import "NICellFactory.h" #import "NIRadioGroup.h" #import "NITableViewModel.h" #import "NIDebuggingTools.h" #import "NIDeviceOrientation.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NIRadioGroupController () @property (nonatomic, readonly, strong) NIRadioGroup* radioGroup; @property (nonatomic, readonly, strong) id<NICell> tappedCell; @property (nonatomic, readonly, strong) NITableViewModel* model; @end @implementation NIRadioGroupController - (void)dealloc { [_radioGroup removeForwarding:self]; } - (id)initWithRadioGroup:(NIRadioGroup *)radioGroup tappedCell:(id<NICell>)tappedCell { if ((self = [super initWithStyle:UITableViewStyleGrouped])) { // A valid radio group must be provided. NIDASSERT(nil != radioGroup); _radioGroup = radioGroup; _tappedCell = tappedCell; _model = [[NITableViewModel alloc] initWithListArray:_radioGroup.allObjects delegate:(id)[NICellFactory class]]; } return self; } - (id)initWithStyle:(UITableViewStyle)style { // Use the initWithRadioGroup initializer. NIDASSERT(NO); return [self initWithRadioGroup:nil tappedCell:nil]; } - (void)viewDidLoad { [super viewDidLoad]; self.tableView.dataSource = self.model; self.tableView.delegate = [self.radioGroup forwardingTo:self.tableView.delegate]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return NIIsSupportedOrientation(toInterfaceOrientation); } #endif - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAllButUpsideDown; } #pragma mark - UITableViewDelegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.tappedCell shouldUpdateCellWithObject:self.radioGroup]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NITableViewActions.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NimbusCore.h" /** * The NITableViewActions class provides an interface for attaching actions to objects in a * NITableViewModel. * * <h2>Basic Use</h2> * * NITableViewModel and NITableViewActions cooperate to solve two related tasks: data * representation and user actions, respectively. A NITableViewModel is composed of objects and * NITableViewActions maintains a mapping of actions to these objects. The object's attached actions * are executed when the user interacts with the cell representing an object. * * <h3>Delegate Forwarding</h3> * * NITableViewActions will apply the correct accessoryType and selectionStyle values to the cell * when the cell is displayed using a mechanism known as <i>delegate chaining</i>. This effect is * achieved by invoking @link NITableViewActions::forwardingTo: forwardingTo:@endlink on the * NITableViewActions instance and providing the appropriate object to forward to (generally * @c self). * @code tableView.delegate = [self.actions forwardingTo:self]; @endcode * * The dataSource property of the table view must be an instance of NITableViewModel. * * @ingroup ModelTools */ @interface NITableViewActions : NIActions <UITableViewDelegate> #pragma mark Forwarding - (id<UITableViewDelegate>)forwardingTo:(id<UITableViewDelegate>)forwardDelegate; - (void)removeForwarding:(id<UITableViewDelegate>)forwardDelegate; #pragma mark Object state - (UITableViewCellAccessoryType)accessoryTypeForObject:(id)object; - (UITableViewCellSelectionStyle)selectionStyleForObject:(id)object; #pragma mark Configurable Properties @property (nonatomic, assign) UITableViewCellSelectionStyle tableViewCellSelectionStyle; @end /** @name Forwarding */ /** * Sets the delegate that table view methods should be forwarded to. * * This method allows you to insert the actions into the call chain for the table view's * delegate methods. * * Example: * @code // Let the actions handle delegate methods and then forward them to whatever delegate was // already assigned. self.tableView.delegate = [self.actions forwardingTo:self.tableView.delegate]; @endcode * * @param forwardDelegate The delegate to forward invocations to. * @returns self so that this method can be chained. * @fn NITableViewActions::forwardingTo: */ /** * Removes the delegate from the forwarding chain. * * If a forwared delegate is about to be released but this object may live on, you must remove the * forwarding in order to avoid invalid access errors at runtime. * * @param forwardDelegate The delegate to stop forwarding invocations to. * @fn NITableViewActions::removeForwarding: */ /** @name Object State */ /** * Returns the accessory type this actions object will apply to a cell for the * given object when it is displayed. * * @param object The object to determine the accessory type for. * @returns the accessory type this object's cell will have. * @fn NITableViewActions::accessoryTypeForObject: */ /** * Returns the cell selection style this actions object will apply to a cell * for the given object when it is displayed. * * @param object The object to determine the selection style for. * @returns the selection style this object's cell will have. * @fn NITableViewActions::selectionStyleForObject: */ /** @name Configurable Properties */ /** * The cell selection style that will be applied to the cell when it is displayed using * delegate forwarding. * * By default this is UITableViewCellSelectionStyleBlue. * * @fn NITableViewActions::tableViewCellSelectionStyle */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NITableViewActions.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NITableViewActions.h" #import "NICellFactory.h" #import "NITableViewModel.h" #import "NimbusCore.h" #import "NIActions+Subclassing.h" #import <objc/runtime.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NITableViewActions() @property (nonatomic, strong) NSMutableSet* forwardDelegates; @end @implementation NITableViewActions - (id)initWithTarget:(id)target { if ((self = [super initWithTarget:target])) { _forwardDelegates = NICreateNonRetainingMutableSet(); _tableViewCellSelectionStyle = UITableViewCellSelectionStyleBlue; } return self; } #pragma mark - Forward Invocations - (BOOL)shouldForwardSelector:(SEL)selector { struct objc_method_description description; description = protocol_getMethodDescription(@protocol(UITableViewDelegate), selector, NO, YES); return (description.name != NULL && description.types != NULL); } - (BOOL)respondsToSelector:(SEL)selector { if ([super respondsToSelector:selector]) { return YES; } else if ([self shouldForwardSelector:selector]) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:selector]) { return YES; } } } return NO; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { NSMethodSignature *signature = [super methodSignatureForSelector:selector]; if (signature == nil) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:selector]) { signature = [delegate methodSignatureForSelector:selector]; } } } return signature; } - (void)forwardInvocation:(NSInvocation *)invocation { BOOL didForward = NO; if ([self shouldForwardSelector:invocation.selector]) { for (id delegate in self.forwardDelegates) { if ([delegate respondsToSelector:invocation.selector]) { [invocation invokeWithTarget:delegate]; didForward = YES; break; } } } if (!didForward) { [super forwardInvocation:invocation]; } } - (id<UITableViewDelegate>)forwardingTo:(id<UITableViewDelegate>)forwardDelegate { [self.forwardDelegates addObject:forwardDelegate]; return self; } - (void)removeForwarding:(id<UITableViewDelegate>)forwardDelegate { [self.forwardDelegates removeObject:forwardDelegate]; } #pragma mark - Object State - (UITableViewCellAccessoryType)accessoryTypeForObject:(id)object { NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; // Detail disclosure indicator takes precedence over regular disclosure indicator. if (nil != action.detailAction || nil != action.detailSelector) { return UITableViewCellAccessoryDetailDisclosureButton; } else if (nil != action.navigateAction || nil != action.navigateSelector) { return UITableViewCellAccessoryDisclosureIndicator; } // We must maintain consistency of modifications to the accessoryType within this call due // to the fact that cells will be reused. return UITableViewCellAccessoryNone; } - (UITableViewCellSelectionStyle)selectionStyleForObject:(id)object { // If the cell is tappable, reflect that in the selection style. NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; if (action.navigateAction || action.tapAction || action.navigateSelector || action.tapSelector) { return self.tableViewCellSelectionStyle; } return UITableViewCellSelectionStyleNone; } #pragma mark - UITableViewDelegate - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]); if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) { NITableViewModel* model = (NITableViewModel *)tableView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectActionable:object]) { cell.accessoryType = [self accessoryTypeForObject:object]; cell.selectionStyle = [self selectionStyleForObject:object]; } else { cell.accessoryType = UITableViewCellAccessoryNone; cell.selectionStyle = UITableViewCellSelectionStyleNone; } } // Forward the invocation along. for (id<UITableViewDelegate> delegate in self.forwardDelegates) { if ([delegate respondsToSelector:_cmd]) { [delegate tableView:tableView willDisplayCell:cell forRowAtIndexPath:indexPath]; } } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]); if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) { NITableViewModel* model = (NITableViewModel *)tableView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectActionable:object]) { NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; BOOL shouldDeselect = NO; if (action.tapAction) { // Tap actions can deselect the row if they return YES. shouldDeselect = action.tapAction(object, self.target, indexPath); } if (action.tapSelector && [self.target respondsToSelector:action.tapSelector]) { NSMethodSignature *methodSignature = [self.target methodSignatureForSelector:action.tapSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature]; invocation.selector = action.tapSelector; if (methodSignature.numberOfArguments >= 3) { [invocation setArgument:&object atIndex:2]; } if (methodSignature.numberOfArguments >= 4) { [invocation setArgument:&indexPath atIndex:3]; } [invocation invokeWithTarget:self.target]; NSUInteger length = invocation.methodSignature.methodReturnLength; if (length > 0) { char *buffer = (void *)malloc(length); memset(buffer, 0, sizeof(char) * length); [invocation getReturnValue:buffer]; for (NSUInteger index = 0; index < length; ++index) { if (buffer[index]) { shouldDeselect = YES; break; } } free(buffer); } } if (shouldDeselect) { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } if (action.navigateAction) { action.navigateAction(object, self.target, indexPath); } if (action.navigateSelector && [self.target respondsToSelector:action.navigateSelector]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self.target performSelector:action.navigateSelector withObject:object withObject:indexPath]; #pragma clang diagnostic pop } } } // Forward the invocation along. for (id<UITableViewDelegate> delegate in self.forwardDelegates) { if ([delegate respondsToSelector:_cmd]) { [delegate tableView:tableView didSelectRowAtIndexPath:indexPath]; } } } - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { NIDASSERT([tableView.dataSource isKindOfClass:[NITableViewModel class]]); if ([tableView.dataSource isKindOfClass:[NITableViewModel class]]) { NITableViewModel* model = (NITableViewModel *)tableView.dataSource; id object = [model objectAtIndexPath:indexPath]; if ([self isObjectActionable:object]) { NIObjectActions* action = [self actionForObjectOrClassOfObject:object]; if (action.detailAction) { action.detailAction(object, self.target, indexPath); } if (action.detailSelector && [self.target respondsToSelector:action.detailSelector]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [self.target performSelector:action.detailSelector withObject:object withObject:indexPath]; #pragma clang diagnostic pop } } } // Forward the invocation along. for (id<UITableViewDelegate> delegate in self.forwardDelegates) { if ([delegate respondsToSelector:_cmd]) { [delegate tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath]; } } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NITableViewModel+Private.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @interface NITableViewModel() @property (nonatomic, strong) NSArray* sections; // Array of NITableViewModelSection @property (nonatomic, strong) NSArray* sectionIndexTitles; @property (nonatomic, strong) NSDictionary* sectionPrefixToSectionIndex; - (void)_resetCompiledData; - (void)_compileDataWithListArray:(NSArray *)listArray; - (void)_compileDataWithSectionedArray:(NSArray *)sectionedArray; - (void)_compileSectionIndex; @end @interface NITableViewModelSection : NSObject + (id)section; @property (nonatomic, copy) NSString* headerTitle; @property (nonatomic, copy) NSString* footerTitle; @property (nonatomic, strong) NSArray* rows; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NITableViewModel.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for weak */ #if NS_BLOCKS_AVAILABLE typedef UITableViewCell* (^NITableViewModelCellForIndexPathBlock)(UITableView* tableView, NSIndexPath* indexPath, id object); #endif // #if NS_BLOCKS_AVAILABLE @protocol NITableViewModelDelegate; #pragma mark Sectioned Array Objects // Classes used when creating NITableViewModels. @class NITableViewModelFooter; // Provides the information for a footer. typedef enum { NITableViewModelSectionIndexNone, // Displays no section index. NITableViewModelSectionIndexDynamic, // Generates a section index from the first letters of the section titles. NITableViewModelSectionIndexAlphabetical, // Generates an alphabetical section index. } NITableViewModelSectionIndex; /** * A non-mutable table view model that complies to the UITableViewDataSource protocol. * * This model allows you to easily create a data source for a UITableView without having to * implement the UITableViewDataSource methods in your UITableViewController. * * This base class is non-mutable, much like an NSArray. You must initialize this model with * the contents when you create it. * * @ingroup TableViewModels */ @interface NITableViewModel : NSObject <UITableViewDataSource> #pragma mark Creating Table View Models // Designated initializer. - (id)initWithDelegate:(id<NITableViewModelDelegate>)delegate; - (id)initWithListArray:(NSArray *)sectionedArray delegate:(id<NITableViewModelDelegate>)delegate; // Each NSString in the array starts a new section. Any other object is a new row (with exception of certain model-specific objects). - (id)initWithSectionedArray:(NSArray *)sectionedArray delegate:(id<NITableViewModelDelegate>)delegate; #pragma mark Accessing Objects - (id)objectAtIndexPath:(NSIndexPath *)indexPath; // This method is not appropriate for performance critical codepaths. - (NSIndexPath *)indexPathForObject:(id)object; #pragma mark Configuration // Immediately compiles the section index. - (void)setSectionIndexType:(NITableViewModelSectionIndex)sectionIndexType showsSearch:(BOOL)showsSearch showsSummary:(BOOL)showsSummary; @property (nonatomic, readonly, assign) NITableViewModelSectionIndex sectionIndexType; // Default: NITableViewModelSectionIndexNone @property (nonatomic, readonly, assign) BOOL sectionIndexShowsSearch; // Default: NO @property (nonatomic, readonly, assign) BOOL sectionIndexShowsSummary; // Default: NO #pragma mark Creating Table View Cells @property (nonatomic, weak) id<NITableViewModelDelegate> delegate; #if NS_BLOCKS_AVAILABLE // If both the delegate and this block are provided, cells returned by this block will be used // and the delegate will not be called. @property (nonatomic, copy) NITableViewModelCellForIndexPathBlock createCellBlock; #endif // #if NS_BLOCKS_AVAILABLE @end /** * A protocol for NITableViewModel to fetch rows to be displayed for the table view. * * @ingroup TableViewModels */ @protocol NITableViewModelDelegate <NSObject> @required /** * Fetches a table view cell at a given index path with a given object. * * The implementation of this method will generally use object to customize the cell. */ - (UITableViewCell *)tableViewModel: (NITableViewModel *)tableViewModel cellForTableView: (UITableView *)tableView atIndexPath: (NSIndexPath *)indexPath withObject: (id)object; @end /** * An object used in sectioned arrays to denote a section footer title. * * Meant to be used in a sectioned array for NITableViewModel. * * <h3>Example</h3> * * @code * [NITableViewModelFooter footerWithTitle:@"Footer"] * @endcode */ @interface NITableViewModelFooter : NSObject + (id)footerWithTitle:(NSString *)title; - (id)initWithTitle:(NSString *)title; @property (nonatomic, copy) NSString* title; @end /** @name Creating Table View Models */ /** * Initializes a newly allocated static model with the given delegate and empty contents. * * This method can be used to create an empty model. * * @fn NITableViewModel::initWithDelegate: */ /** * Initializes a newly allocated static model with the contents of a list array. * * A list array is a one-dimensional array that defines a flat list of rows. There will be * no sectioning of contents in any way. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * nil]; * [[NIStaticTableViewModel alloc] initWithListArray:contents delegate:self]; * @endcode * * @fn NITableViewModel::initWithListArray:delegate: */ /** * Initializes a newly allocated static model with the contents of a sectioned array. * * A sectioned array is a one-dimensional array that defines a list of sections and each * section's contents. Each NSString begins a new section and any other object defines a * row for the current section. * * <h3>Example</h3> * * @code * NSArray* contents = * [NSArray arrayWithObjects: * @"Section 1", * [NSDictionary dictionaryWithObject:@"Row 1" forKey:@"title"], * [NSDictionary dictionaryWithObject:@"Row 2" forKey:@"title"], * @"Section 2", * // This section is empty. * @"Section 3", * [NSDictionary dictionaryWithObject:@"Row 3" forKey:@"title"], * [NITableViewModelFooter footerWithTitle:@"Footer"], * nil]; * [[NIStaticTableViewModel alloc] initWithSectionedArray:contents delegate:self]; * @endcode * * @fn NITableViewModel::initWithSectionedArray:delegate: */ /** @name Accessing Objects */ /** * Returns the object at the given index path. * * If no object exists at the given index path (an invalid index path, for example) then nil * will be returned. * * @fn NITableViewModel::objectAtIndexPath: */ /** * Returns the index path of the given object within the model. * * If the model does not contain the object then nil will be returned. * * @fn NITableViewModel::indexPathForObject: */ /** @name Configuration */ /** * Configures the model's section index properties. * * Calling this method will compile the section index depending on the index type chosen. * * @param sectionIndexType The type of section index to display. * @param showsSearch Whether or not to show the search icon at the top of the index. * @param showsSummary Whether or not to show the summary icon at the bottom of the index. * @fn NITableViewModel::setSectionIndexType:showsSearch:showsSummary: */ /** * The section index type. * * You will likely use NITableViewModelSectionIndexAlphabetical in practice. * * NITableViewModelSectionIndexNone by default. * * @fn NITableViewModel::sectionIndexType */ /** * Whether or not the search symbol will be shown in the section index. * * NO by default. * * @fn NITableViewModel::sectionIndexShowsSearch */ /** * Whether or not the summary symbol will be shown in the section index. * * NO by default. * * @fn NITableViewModel::sectionIndexShowsSummary */ /** @name Creating Table View Cells */ /** * A delegate used to fetch table view cells for the data source. * * @fn NITableViewModel::delegate */ #if NS_BLOCKS_AVAILABLE /** * A block used to create a UITableViewCell for a given object. * * @fn NITableViewModel::createCellBlock */ #endif // #if NS_BLOCKS_AVAILABLE
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NITableViewModel.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NITableViewModel.h" #import "NITableViewModel+Private.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NITableViewModel #if NS_BLOCKS_AVAILABLE #endif // #if NS_BLOCKS_AVAILABLE - (id)initWithDelegate:(id<NITableViewModelDelegate>)delegate { if ((self = [super init])) { self.delegate = delegate; _sectionIndexType = NITableViewModelSectionIndexNone; _sectionIndexShowsSearch = NO; _sectionIndexShowsSummary = NO; [self _resetCompiledData]; } return self; } - (id)initWithListArray:(NSArray *)listArray delegate:(id<NITableViewModelDelegate>)delegate { if ((self = [self initWithDelegate:delegate])) { [self _compileDataWithListArray:listArray]; } return self; } - (id)initWithSectionedArray:(NSArray *)sectionedArray delegate:(id<NITableViewModelDelegate>)delegate { if ((self = [self initWithDelegate:delegate])) { [self _compileDataWithSectionedArray:sectionedArray]; } return self; } - (id)init { return [self initWithDelegate:nil]; } #pragma mark - Compiling Data - (void)_resetCompiledData { self.sections = nil; self.sectionIndexTitles = nil; self.sectionPrefixToSectionIndex = nil; } - (void)_compileDataWithListArray:(NSArray *)listArray { [self _resetCompiledData]; if (nil != listArray) { NITableViewModelSection* section = [NITableViewModelSection section]; section.rows = listArray; self.sections = [NSArray arrayWithObject:section]; } } - (void)_compileDataWithSectionedArray:(NSArray *)sectionedArray { [self _resetCompiledData]; NSMutableArray* sections = [NSMutableArray array]; NSString* currentSectionHeaderTitle = nil; NSString* currentSectionFooterTitle = nil; NSMutableArray* currentSectionRows = nil; for (id object in sectionedArray) { BOOL isSection = [object isKindOfClass:[NSString class]]; BOOL isSectionFooter = [object isKindOfClass:[NITableViewModelFooter class]]; NSString* nextSectionHeaderTitle = nil; if (isSection) { nextSectionHeaderTitle = object; } else if (isSectionFooter) { NITableViewModelFooter* footer = object; currentSectionFooterTitle = footer.title; } else { if (nil == currentSectionRows) { currentSectionRows = [[NSMutableArray alloc] init]; } [currentSectionRows addObject:object]; } // A section footer or title has been encountered, if (nil != nextSectionHeaderTitle || nil != currentSectionFooterTitle) { if (nil != currentSectionHeaderTitle || nil != currentSectionFooterTitle || nil != currentSectionRows) { NITableViewModelSection* section = [NITableViewModelSection section]; section.headerTitle = currentSectionHeaderTitle; section.footerTitle = currentSectionFooterTitle; section.rows = currentSectionRows; [sections addObject:section]; } currentSectionRows = nil; currentSectionHeaderTitle = nextSectionHeaderTitle; currentSectionFooterTitle = nil; } } // Commit any unfinished sections. if ([currentSectionRows count] > 0 || nil != currentSectionHeaderTitle) { NITableViewModelSection* section = [NITableViewModelSection section]; section.headerTitle = currentSectionHeaderTitle; section.footerTitle = currentSectionFooterTitle; section.rows = currentSectionRows; [sections addObject:section]; } currentSectionRows = nil; // Update the compiled information for this data source. self.sections = sections; } - (void)_compileSectionIndex { _sectionIndexTitles = nil; // Prime the section index and the map NSMutableArray* titles = nil; NSMutableDictionary* sectionPrefixToSectionIndex = nil; if (NITableViewModelSectionIndexNone != _sectionIndexType) { titles = [NSMutableArray array]; sectionPrefixToSectionIndex = [NSMutableDictionary dictionary]; // The search symbol is always first in the index. if (_sectionIndexShowsSearch) { [titles addObject:UITableViewIndexSearch]; } } // A dynamic index shows the first letter of every section in the index in whatever order the // sections are ordered (this may not be alphabetical). if (NITableViewModelSectionIndexDynamic == _sectionIndexType) { for (NITableViewModelSection* section in _sections) { NSString* headerTitle = section.headerTitle; if ([headerTitle length] > 0) { NSString* prefix = [headerTitle substringToIndex:1]; [titles addObject:prefix]; } } } else if (NITableViewModelSectionIndexAlphabetical == _sectionIndexType) { // Use the localized indexed collation to create the index. In English, this will always be // the entire alphabet. NSArray* sectionIndexTitles = [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]; // The localized indexed collection sometimes includes a # for summaries, but we might // not want to show a summary in the index, so prune it out. It's not guaranteed that // a # will actually be included in the section index titles, so we always attempt to // remove it for consistency's sake and then add it back down below if it is requested. for (NSString* letter in sectionIndexTitles) { if (![letter isEqualToString:@"#"]) { [titles addObject:letter]; } } } // Add the section summary symbol if it was requested. if (_sectionIndexShowsSummary) { [titles addObject:@"#"]; } // Build the prefix => section index map. if (NITableViewModelSectionIndexNone != _sectionIndexType) { // Map all of the sections to indices. NSInteger sectionIndex = 0; for (NITableViewModelSection* section in _sections) { NSString* headerTitle = section.headerTitle; if ([headerTitle length] > 0) { NSString* prefix = [headerTitle substringToIndex:1]; if (nil == [sectionPrefixToSectionIndex objectForKey:prefix]) { [sectionPrefixToSectionIndex setObject:[NSNumber numberWithInteger:sectionIndex] forKey:prefix]; } } ++sectionIndex; } // Map the unmapped section titles to the next closest earlier section. NSInteger lastIndex = 0; for (NSString* title in titles) { NSString* prefix = [title substringToIndex:1]; if (nil != [sectionPrefixToSectionIndex objectForKey:prefix]) { lastIndex = [[sectionPrefixToSectionIndex objectForKey:prefix] intValue]; } else { [sectionPrefixToSectionIndex setObject:[NSNumber numberWithInteger:lastIndex] forKey:prefix]; } } } self.sectionIndexTitles = titles; self.sectionPrefixToSectionIndex = sectionPrefixToSectionIndex; } #pragma mark - UITableViewDataSource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return self.sections.count; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { NIDASSERT((section >= 0 && (NSUInteger)section < self.sections.count) || 0 == self.sections.count); if (section >= 0 && (NSUInteger)section < self.sections.count) { return [[self.sections objectAtIndex:section] headerTitle]; } else { return nil; } } - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { NIDASSERT((section >= 0 && (NSUInteger)section < self.sections.count) || 0 == self.sections.count); if (section >= 0 && (NSUInteger)section < self.sections.count) { return [[self.sections objectAtIndex:section] footerTitle]; } else { return nil; } } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // This is a static model; nothing can be edited. return NO; } - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return self.sectionIndexTitles; } - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { if (tableView.tableHeaderView) { if (index == 0 && [self.sectionIndexTitles count] > 0 && [self.sectionIndexTitles objectAtIndex:0] == UITableViewIndexSearch) { // This is a hack to get the table header to appear when the user touches the // first row in the section index. By default, it shows the first row, which is // not usually what you want. [tableView scrollRectToVisible:tableView.tableHeaderView.bounds animated:NO]; return -1; } } NSString* letter = [title substringToIndex:1]; NSNumber* sectionIndex = [self.sectionPrefixToSectionIndex objectForKey:letter]; return (nil != sectionIndex) ? [sectionIndex intValue] : -1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NIDASSERT((NSUInteger)section < self.sections.count || 0 == self.sections.count); if ((NSUInteger)section < self.sections.count) { return [[[self.sections objectAtIndex:section] rows] count]; } else { return 0; } } - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { id object = [self objectAtIndexPath:indexPath]; UITableViewCell* cell = nil; #if NS_BLOCKS_AVAILABLE if (nil != self.createCellBlock) { cell = self.createCellBlock(tableView, indexPath, object); } #endif if (nil == cell) { cell = [self.delegate tableViewModel:self cellForTableView:tableView atIndexPath:indexPath withObject:object]; } return cell; } #pragma mark - Public - (id)objectAtIndexPath:(NSIndexPath *)indexPath { if (nil == indexPath) { return nil; } NSInteger section = [indexPath section]; NSInteger row = [indexPath row]; id object = nil; NIDASSERT((NSUInteger)section < self.sections.count); if ((NSUInteger)section < self.sections.count) { NSArray* rows = [[self.sections objectAtIndex:section] rows]; NIDASSERT((NSUInteger)row < rows.count); if ((NSUInteger)row < rows.count) { object = [rows objectAtIndex:row]; } } return object; } - (NSIndexPath *)indexPathForObject:(id)object { if (nil == object) { return nil; } NSArray *sections = self.sections; for (NSUInteger sectionIndex = 0; sectionIndex < [sections count]; sectionIndex++) { NSArray* rows = [[sections objectAtIndex:sectionIndex] rows]; for (NSUInteger rowIndex = 0; rowIndex < [rows count]; rowIndex++) { if ([object isEqual:[rows objectAtIndex:rowIndex]]) { return [NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex]; } } } return nil; } - (void)setSectionIndexType:(NITableViewModelSectionIndex)sectionIndexType showsSearch:(BOOL)showsSearch showsSummary:(BOOL)showsSummary { if (_sectionIndexType != sectionIndexType || _sectionIndexShowsSearch != showsSearch || _sectionIndexShowsSummary != showsSummary) { _sectionIndexType = sectionIndexType; _sectionIndexShowsSearch = showsSearch; _sectionIndexShowsSummary = showsSummary; [self _compileSectionIndex]; } } @end @implementation NITableViewModelFooter + (NITableViewModelFooter *)footerWithTitle:(NSString *)title { return [[self alloc] initWithTitle:title]; } - (id)initWithTitle:(NSString *)title { if ((self = [super init])) { self.title = title; } return self; } @end @implementation NITableViewModelSection + (id)section { return [[self alloc] init]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/models/src/NimbusModels.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma mark - Nimbus Models /** * @defgroup NimbusModels Nimbus Models * @{ * * <div id="github" feature="models"></div> * * A model is an implementation of a data source protocol. * * Data sources are required by various UI components throughout UIKit and Nimbus. * It can be painful to have to rewrite the same data source logic over and over * again. Nimbus models allow you to separate the data source logic from your view * controller and recycle common functionality throughout your application. You'll * find that your view controller can then focus on the broader implementation details * rather than implementing dozens of data source methods. * * <h2>Vanilla UIKit vs Nimbus Models</h2> * * If you would like to see an example of Nimbus models being used, check out * the ModelCatalog example application. */ #pragma mark * Table View Models /** * @defgroup TableViewModels Table View Models * * Nimbus table view models make building table views remarkably easy. Rather than implement * the data source methods in each table view controller, you assign a model to * self.tableView.dataSource and only think about row creation. * * Nimbus table view models implement many of the standard table view data source methods, * including methods for section titles, grouped rows, and section indices. By * providing this functionality in one object, Nimbus provides much more * efficient implementations than one-off implementations that might otherwise * be copied from one controller to another. * * <h2>Creating Generic Static Models</h2> * * In order to use the Nimbus table view model you create a model, assign * it to your table view's data source after the table view has been created, and implement * the model delegate to create the table view cells. You can use the * @link TableCellFactory Nimbus cell factory@endlink to avoid implementing the model * delegate. * * Below is an example of creating a basic list model: * * @code NSArray* tableContents = [NSArray arrayWithObjects: [NITitleCellObject objectWithTitle:@"Row 1"], [NITitleCellObject objectWithTitle:@"Row 2"], [NITitleCellObject objectWithTitle:@"Row 3"], nil]; _model = [[NITableViewModel alloc] initWithListArray:tableContents delegate:self]; * @endcode * * Below is an example of creating a basic sectioned model: * * @code NSArray* tableContents = [NSArray arrayWithObjects: @"Section Title", [NITitleCellObject objectWithTitle:@"Row 1"], [NITitleCellObject objectWithTitle:@"Row 2"], @"Section Title", [NITitleCellObject objectWithTitle:@"Row 3"], nil]; _model = [[NITableViewModel alloc] initWithSectionedArray:tableContents delegate:self]; * @endcode * * Both of the above examples would implement the model delegate like so: * * @code - (UITableViewCell *)tableViewModel: (NITableViewModel *)tableViewModel cellForTableView: (UITableView *)tableView atIndexPath: (NSIndexPath *)indexPath withObject: (id)object { UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"row"]; if (nil == cell) { cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: @"row"] autorelease]; } cell.textLabel.text = [object objectForKey:@"title"]; return cell; } * @endcode * * <h2>Creating Forms</h2> * * Let's say you want to create a form for a user to enter their username and password. You * can easily do this with Nimbus using the @link TableCellFactory Nimbus cell factory@endlink * and the Nimbus form elements from the @link TableCellCatalog table cell catalog@endlink. * * @code NSArray* tableContents = [NSArray arrayWithObjects: @"Sign In", [NITextInputFormElement textInputElementWithID:kUsernameField placeholderText:@"Username" value:nil], [NITextInputFormElement passwordInputElementWithID:kPasswordField placeholderText:@"Password" value:nil], nil]; _model = [[NITableViewModel alloc] initWithSectionedArray:tableContents delegate:(id)[NICellFactory class]]; * @endcode * * When the user then hits the button to sign in, you can grab the values from the model by using * the elementWithID: category method added to NITableViewModel by the form support. * * @code NSString* username = [[_model elementWithID:kUsernameField] value]; NSString* password = [[_model elementWithID:kPasswordField] value]; * @endcode * * See example: @link ExampleStaticTableModel.m Static Table Model Creation@endlink */ #pragma mark * Table Cell Factory /** * @defgroup TableCellFactory Table Cell Factory * * A table cell factory automatically creates UITableViewCells from objects. * * The Nimbus table cell factory works by requiring that objects implement a basic protocol, * NICellObject, which sets up a binding from the object to a specific cell implementation. * This cell implementation can optionally implement the NICell protocol. In practice this is * nearly always the case. You then simply use the factory in your table's data source and * the factory will handle the rest. This allows you to completely separate presentation from * data in your table view controllers. * * <h2>A Simple Example: A Twitter Application</h2> * * Let's say you want to build a Twitter news feed. We'll assume you've * already figured out the network requests and now have individual tweets itching to be displayed. * To use the Nimbus factory you will need two different classes: one for the tweet object * and its data, and another for the tweet table view cell. Let's call them Tweet and * TweetCell, respectively. You may even already have a Tweet object. * * <h3>Implement the NICellObject Protocol</h3> * * You must first implement the NICellObject protocol in your Tweet object. We want to link * the TweetCell table view cell to the Tweet object so that the factory can create a TweetCell * when it needs to present the Tweet object. * * @code @interface Tweet : NSObject <NICellObject> { // ... } @end @implementation Tweet - (Class)cellClass { return [TweetCell class]; } @end * @endcode * * Now that we've pointed the Tweet object to the TweetCell class, let's make the * table controller use the NICellFactory. * * <h3>Using the Factory</h3> * * There are a few ways you can use the factory in your code. We'll walk through increasingly * Nimbus-like implementations, starting with a vanilla UIKit implementation. * * The following vanilla UIKit implementation has the advantage of allowing you to use * NICellFactory in your existing code base without requiring a full rewrite of your data * source. If you are attempting to switch to a pure Nimbus implementation using the cell factory * then this is a good first step because it is the least invasive. * * @code - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { // Note: You must fetch the object at this index path somehow. The objectAtIndexPath: // is simply an example; replace it with your own implementation. id object = [self objectAtIndexPath:indexPath]; UITableViewCell* cell = [NICellFactory tableViewModel:nil cellForTableView:tableView atIndexPath:indexPath withObject:object]; if (nil == cell) { // Here would be whatever code you were originally using to create cells. nil is only returned // when the factory wasn't able to create a cell, likely due to the NICellObject protocol // not being implemented for the given object. As you implement these protocols on // more objects the factory will automatically start returning the correct cells // and you can start removing this special-case logic. } return cell; } * @endcode * * This next implementation is what your vanilla data source implementation would look like once * you have no more custom cell creation code. * * @code - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { // Note: You must fetch the object at this index path somehow. The objectAtIndexPath: // is simply an example; replace it with your own implementation. id object = [self objectAtIndexPath:indexPath]; // Only use the factory to create cells now that every object used in this controller // implements the factory protocols. return [NICellFactory tableViewModel:nil cellForTableView:tableView atIndexPath:indexPath withObject:object]; } * @endcode * * If you are using Nimbus models then your code gets even simpler because the object is passed * to your model delegate method. * * @code - (UITableViewCell *)tableViewModel: (NITableViewModel *)tableViewModel cellForTableView: (UITableView *)tableView atIndexPath: (NSIndexPath *)indexPath withObject: (id)object { // The model gives us the object, making this much simpler and likely more efficient than the vanilla UIKit implementation. return [NICellFactory tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object]; } * @endcode * * And finally, if you require no custom code in your model delegate, the above example can * be shortened to a one-liner when you initialize the model: * * @code // This is functionally identical to implementing the delegate in this controller and simply // calling the factory method. _model.delegate = (id)[NICellFactory class]; * @endcode * * <h3>Customizing the Cell</h3> * * We want to customize the cells as they are presented, otherwise all of the cells will look * the same. After our TweetCell object is created in the factory, the factory will call * the @link NICell::shouldUpdateCellWithObject: shouldUpdateCellWithObject:@endlink method * on the cell, if it is implemented. Remember that cells are reused in table views and that * any modification you may make to the cell could still be present the next time this cell * is updated with an object. * * @code - (BOOL)shouldUpdateCellWithObject:(id)object { // We can be rest assured that `object` is a Tweet object because that's how we set up // the bindings. If more than one type of object maps to this cell class then we'd have // to check the object type accordingly. Tweet* tweet = object; self.textLabel.text = tweet.text; // Returning YES or NO here is intended purely for subclassing purposes. Returning YES means // that the object changed the cell in some way. return YES; } * @endcode * * <h3>Conclusions</h3> * * The Nimbus cell factory can greatly reduce the amount of code you have to write in your * table controllers while separating the data from the presentation. You can slowly ease * yourself into using the factory if you already have a large existing code base. * * If you are migrating from Three20, you will find that Nimbus' table factory is very similar * to TTTableViewController, though greatly simplified and decoupled from the rest of the Three20 * ecosystem. Where Three20 provided a tightly integrated solution, Nimbus allows you to plug * in the factory where it makes sense. */ #pragma mark * Table Cell Catalog /** * @defgroup TableCellCatalog Table Cell Catalog * * This is a catalog of Nimbus' pre-built cells and objects for use in UITableViews. * * All of these cells are designed primarily to be used with the * @link TableCellFactory Nimbus cell factory@endlink, though it is entirely possible to use * the cells in a vanilla UIKit application as well. * * <h2>Form Element Catalog</h2> * * Building forms with Nimbus is incredibly easy thanks to the pre-built form elements. The * available form elements are listed below. * * Form elements require an element ID that can be used to differentiate between the form * elements, much like in HTML. If you are using the table cell factory then the element ID * will be assigned to the cell's view tag and the control tags as well. Let's say you want * to add a text input element that is disabled under certain conditions. Your code would look * something like the following: * * @code // In your model, create an element with the delegate provided. [NITextInputFormElement elementWithID:kUsernameField placeholderText:@"Username" value:nil delegate:self], // And then implement the UITextFieldDelegate - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { if (textField.tag == kUsernameField) { return NO; } return YES; } * @endcode * * <h3>NITextInputFormElement</h3> * * @image html NITextInputCellExample1.png "NITextInputFormElement => NITextInputFormElementCell" * * Example use in a NITableViewModel: * @code // Create a text input field. [NITextInputFormElement textInputElementWithID:kUsernameField placeholderText:@"Username" value:nil], // Create a password input field [NITextInputFormElement passwordInputElementWithID:kPasswordField placeholderText:@"Password" value:nil], * @endcode * * <h3>NISwitchFormElement</h3> * * @image html NISwitchFormElementCellExample1.png "NISwitchFormElement => NISwitchFormElementCell" * * Example use in a NITableViewModel: * @code [NISwitchFormElement switchElementWithID:kPushNotifications labelText:@"Push Notifications" value:NO], * @endcode * */ #pragma mark * Table Cell Backgrounds /** * @defgroup TableCellBackgrounds Table Cell Backgrounds * * NICellBackground is a tool for creating backgrounds that can be used to customize cells in * UITableViews. */ #pragma mark * Model Tools /** * @defgroup ModelTools Model Tools * * Model tools are objects that abstract common functionality used in view controllers. * * <h2>Radio Groups</h2> * * One commonly-required feature for table views is radio button functionality. This is useful when * you need the user to make a choice from a set of options. Implementing this is trivial with the * Nimbus NIRadioGroup object. * * The radio group object allows you to map a set of table objects to a group of identifiers and * then support radio button interactions. You can find a working example of this in the * ModelCatalog sample application. * * Provided below is a quick overview of implementing the iOS Settings app's notifications page. * @code // We first define the enumeration of identifiers that we will use to map the table objects // to unique identifiers. typedef enum { AppSortManual, AppSortByTime, } AppSort; // You will create and retain a radio group object for the lifecycle of your controller. @property (nonatomic, retain) NIRadioGroup* radioGroup; - (void)refreshModel { id manual = [NITitleCellObject cellWithTitle:@"Manually"]; id byTime = [NITitleCellObject cellWithTitle:@"By Time"]; NSArray* contents = [NSArray arrayWithObjects: @"Sort Apps:", manual, byTime, nil]; self.model = [[NITableViewModel alloc] initWithSectionedArray:contents delegate:(id)[NICellFactory class]]; self.tableView.dataSource = self.model; self.radioGroup = [[[NIRadioGroup alloc] init] autorelease]; // Selection notifications are sent through the delegate. self.radioGroup.delegate = self; // Map the objects to their corresponding identifiers. [self.radioGroup mapObject:manual toIdentifier:AppSortManual]; [self.radioGroup mapObject:byTime toIdentifier:AppSortByTime]; // Set the initial selection. self.radioGroup.selectedIdentifier = AppSortManual; // Insert the radio group into the delegate call chain. self.tableView.delegate = [self.radioGroup forwardingTo:self.tableView.delegate]; [self.tableView reloadData]; } - (void)radioGroup:(NIRadioGroup *)radioGroup didSelectIdentifier:(NSInteger)identifier { NSLog(@"Radio group selection changed: %d", identifier); } @endcode * * <h2>Table View Actions</h2> * * Separating actions from presentation is an important aspect in simplifying table view cell * design. It can be tempting to add delegate and selector properties to cells, but this ends up * forcing a lot of logic to be written on the cell level so that the cells accurately represent * their actionable state. * * Nimbus provides a solution with NITableViewActions. NITableViewActions manages the cell <=> * action mapping by inserting itself in the delegate call chain invocation forwarding. When cells * are displayed, their accessoryType and selectionStyle are updated to reflect the actions that * have been attached to them. When cells are tapped, the correct set of actions are performed. * * Below is an example of implementing the "General" page of the Settings app. * @code // You will create and retain an actions object for the lifecycle of your controller. @property (nonatomic, retain) NITableViewActions* actions; - (void)refreshModel { id about = [NITitleCellObject cellWithTitle:@"About"]; id softwareUpdate = [NITitleCellObject cellWithTitle:@"Software Update"]; NSArray* contents = [NSArray arrayWithObjects: @"", about, softwareUpdate, nil]; self.model = [[NITableViewModel alloc] initWithSectionedArray:contents delegate:(id)[NICellFactory class]]; self.tableView.dataSource = self.model; // The controller we provide here will be passed to the action blocks. self.actions = [[[NITableViewActions alloc] initWithController:self] autorelease]; [self.actions attachNavigationAction:NIPushControllerAction([AboutViewController class]) toObject:about]; [self.actions attachNavigationAction:NIPushControllerAction([SoftwareUpdateViewController class]) toObject:softwareUpdate]; // Insert the actions into the delegate call chain. self.tableView.delegate = [self.actions forwardingTo:self.tableView.delegate]; [self.tableView reloadData]; } @endcode */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NITableViewModel.h" #import "NIMutableTableViewModel.h" #import "NICellBackgrounds.h" #import "NICellCatalog.h" #import "NICellFactory.h" #import "NIFormCellCatalog.h" #import "NIRadioGroup.h" #import "NIRadioGroupController.h" #import "NITableViewActions.h" /**@}*/
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkcontrollers/src/NINetworkTableViewController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> /** * The NINetworkTableViewController class provides a similar implementation to UITableViewController * but with a more structured view hierarchy. * * UITableViewController's self.view \em is its self.tableView. This can be problematic if you want * to introduce any sibling views that have a higher or lower z-index. This class provides an * implementation that, to the best of its abilities, mimics the functionality of * UITableViewController in every way but one: self.tableView is a subview of self.view. This simple * difference allows us to add new views above the tableView in the z-index. * * In this particular implementation we include an activity indicator component which may be used * to show that data is currently being loaded. * * @ingroup NimbusNetworkControllers */ @interface NINetworkTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> // Designated initializer. - (id)initWithStyle:(UITableViewStyle)style activityIndicatorStyle:(UIActivityIndicatorViewStyle)activityIndicatorStyle; @property (nonatomic, strong) UITableView* tableView; @property (nonatomic, strong) UIActivityIndicatorView *activityIndicator; @property (nonatomic, assign) BOOL clearsSelectionOnViewWillAppear; // Default: YES - (void)setIsLoading:(BOOL)isLoading; @end /** * Sets the loading state of the view controller. * * @param isLoading When YES, the table view will be hidden and an activity indicator will be * shown centered in the view controller's view. * When NO, the table view will be shown and the activity indicator hidden. * @fn NINetworkTableViewController::setIsLoading: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkcontrollers/src/NINetworkTableViewController.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NINetworkTableViewController.h" #import "NimbusCore+Additions.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NINetworkTableViewController() @property (nonatomic, assign) UIActivityIndicatorViewStyle activityIndicatorStyle; @property (nonatomic, assign) UITableViewStyle tableViewStyle; @end @implementation NINetworkTableViewController - (void)dealloc { _tableView.delegate = nil; _tableView.dataSource = nil; } - (id)initWithStyle:(UITableViewStyle)style activityIndicatorStyle:(UIActivityIndicatorViewStyle)activityIndicatorStyle { if ((self = [super initWithNibName:nil bundle:nil])) { self.tableViewStyle = style; self.activityIndicatorStyle = activityIndicatorStyle; self.clearsSelectionOnViewWillAppear = YES; } return self; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { return [self initWithStyle:UITableViewStylePlain activityIndicatorStyle:UIActivityIndicatorViewStyleGray]; } - (void)loadView { [super loadView]; self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:self.tableViewStyle]; self.tableView.autoresizingMask = UIViewAutoresizingFlexibleDimensions; self.tableView.delegate = self; self.tableView.dataSource = self; [self.view addSubview:self.tableView]; self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorStyle]; self.activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleMargins; [self.activityIndicator sizeToFit]; self.activityIndicator.frame = NIFrameOfCenteredViewWithinView(self.activityIndicator, self.view); [self.view addSubview:self.activityIndicator]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (self.clearsSelectionOnViewWillAppear) { [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:animated]; } } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return nil; } #pragma mark - Public - (void)setIsLoading:(BOOL)isLoading { self.tableView.hidden = isLoading; if (isLoading) { [self.activityIndicator startAnimating]; } else { [self.activityIndicator stopAnimating]; } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkcontrollers/src/NimbusNetworkControllers.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusNetworkControllers Nimbus Network Controllers * @{ * * <div id="github" feature="networkcontrollers"></div> * * View controllers that display loading states while they load information from the network or * disk. * * Whether you are loading data from the disk or from the network, it is important to present * the fact that information is loading to your user. This ensures that your application feels * responsive and also comforts the user by letting them know that your application is working * on something. * * The Nimbus network controllers are designed to provide functionality for the most common states * used when loading resources asynchronously. These states include: * * - Fresh load: when no data exists and we are loading new data. * - Refresh load: when data exists and we are reloading new data. * - Error: the previous request failed. */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NINetworkTableViewController.h" /**@}*/
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NIImageProcessing.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NINetworkImageView.h" // For NINetworkImageViewScaleOptions #import "NimbusCore.h" @interface NIImageProcessing : NSObject /** @name Image Modifications */ /** * Takes a source image and resizes/crops it according to a set of display properties. * * On devices with retina displays, the resulting image will be returned at the correct * resolution for the device. * * @param src The source image. * @param contentMode The content mode to use when cropping and resizing the image. * @param cropRect An initial crop rect to apply to the src image. * @param displaySize The requested display size for the image. The resulting image * may or may not match these dimensions depending on the scale * options being used. * @param scaleOptions See the NINetworkImageViewScaleOptions documentation for more * details. * @param interpolationQuality The interpolation quality to use when resizing the image. * * @returns The resized and cropped image. */ + (UIImage *)imageFromSource:(UIImage *)src withContentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect displaySize:(CGSize)displaySize scaleOptions:(NINetworkImageViewScaleOptions)scaleOptions interpolationQuality:(CGInterpolationQuality)interpolationQuality; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NIImageProcessing.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIImageProcessing.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIImageProcessing /** * Calculate the source rect in the source image from which we'll extract the image before drawing * it in the destination image. */ + (CGRect)sourceRectWithImageSize:(CGSize)imageSize displaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode { if (UIViewContentModeScaleToFill == contentMode) { // Scale to fill draws the original image by squashing it to fit the destination's // aspect ratio, so the source and destination rects aren't modified. return CGRectMake(0, 0, imageSize.width, imageSize.height); } else if (UIViewContentModeScaleAspectFit == contentMode) { // Aspect fit grabs the entire original image and squashes it down to a frame that fits // the destination and leaves the unfilled space transparent. return CGRectMake(0, 0, imageSize.width, imageSize.height); } else if (UIViewContentModeScaleAspectFill == contentMode) { // Aspect fill requires that we take the destination rectangle and "fit" it within the // source rectangle; this gives us the area of the source image we'll crop out to draw into // the destination image. CGFloat scale = MIN(imageSize.width / displaySize.width, imageSize.height / displaySize.height); CGSize scaledDisplaySize = CGSizeMake(displaySize.width * scale, displaySize.height * scale); return CGRectMake(floorf((imageSize.width - scaledDisplaySize.width) / 2), floorf((imageSize.height - scaledDisplaySize.height) / 2), scaledDisplaySize.width, scaledDisplaySize.height); } else if (UIViewContentModeCenter == contentMode) { // We need to cut out a hole the size of the display in the center of the source image. return CGRectMake(floorf((imageSize.width - displaySize.width) / 2), floorf((imageSize.width - displaySize.width) / 2), displaySize.width, displaySize.height); } else if (UIViewContentModeTop == contentMode) { // We need to cut out a hole the size of the display in the top center of the source image. return CGRectMake(floorf((imageSize.width - displaySize.width) / 2), 0, displaySize.width, displaySize.height); } else if (UIViewContentModeBottom == contentMode) { // We need to cut out a hole the size of the display in the bottom center of the source image. return CGRectMake(floorf((imageSize.width - displaySize.width) / 2), imageSize.height - displaySize.height, displaySize.width, displaySize.height); } else if (UIViewContentModeLeft == contentMode) { // We need to cut out a hole the size of the display in the left center of the source image. return CGRectMake(0, floorf((imageSize.width - displaySize.width) / 2), displaySize.width, displaySize.height); } else if (UIViewContentModeRight == contentMode) { // We need to cut out a hole the size of the display in the right center of the source image. return CGRectMake(imageSize.width - displaySize.width, floorf((imageSize.width - displaySize.width) / 2), displaySize.width, displaySize.height); } else if (UIViewContentModeTopLeft == contentMode) { // We need to cut out a hole the size of the display in the top left of the source image. return CGRectMake(0, 0, displaySize.width, displaySize.height); } else if (UIViewContentModeTopRight == contentMode) { // We need to cut out a hole the size of the display in the top right of the source image. return CGRectMake(imageSize.width - displaySize.width, 0, displaySize.width, displaySize.height); } else if (UIViewContentModeBottomLeft == contentMode) { // We need to cut out a hole the size of the display in the bottom left of the source image. return CGRectMake(0, imageSize.height - displaySize.height, displaySize.width, displaySize.height); } else if (UIViewContentModeBottomRight == contentMode) { // We need to cut out a hole the size of the display in the bottom right of the source image. return CGRectMake(imageSize.width - displaySize.width, imageSize.height - displaySize.height, displaySize.width, displaySize.height); } else { // Not implemented NIDERROR(@"The following content mode has not been implemented: %d", contentMode); return CGRectMake(0, 0, imageSize.width, imageSize.height); } } /** * Calculate the destination rect in the destination image where we will draw the cropped source * image. */ + (CGRect)destinationRectWithImageSize:(CGSize)imageSize displaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode { if (UIViewContentModeScaleAspectFit == contentMode) { // Fit the image right in the center of the source frame and maintain the aspect ratio. CGFloat scale = MIN(displaySize.width / imageSize.width, displaySize.height / imageSize.height); CGSize scaledImageSize = CGSizeMake(imageSize.width * scale, imageSize.height * scale); return CGRectMake(floorf((displaySize.width - scaledImageSize.width) / 2), floorf((displaySize.height - scaledImageSize.height) / 2), scaledImageSize.width, scaledImageSize.height); } else if (UIViewContentModeScaleToFill == contentMode || UIViewContentModeScaleAspectFill == contentMode || UIViewContentModeCenter == contentMode || UIViewContentModeTop == contentMode || UIViewContentModeBottom == contentMode || UIViewContentModeLeft == contentMode || UIViewContentModeRight == contentMode || UIViewContentModeTopLeft == contentMode || UIViewContentModeTopRight == contentMode || UIViewContentModeBottomLeft == contentMode || UIViewContentModeBottomRight == contentMode) { // We're filling the entire destination, so the destination rect is the display rect. return CGRectMake(0, 0, displaySize.width, displaySize.height); } else { // Not implemented NIDERROR(@"The following content mode has not been implemented: %d", contentMode); return CGRectMake(0, 0, displaySize.width, displaySize.height); } } + (UIImage *)imageFromSource:(UIImage *)src withContentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect displaySize:(CGSize)displaySize scaleOptions:(NINetworkImageViewScaleOptions)scaleOptions interpolationQuality:(CGInterpolationQuality)interpolationQuality { UIImage* resultImage = src; CGImageRef srcImageRef = src.CGImage; CGImageRef croppedImageRef = nil; CGImageRef trimmedImageRef = nil; CGRect srcRect = CGRectMake(0, 0, src.size.width, src.size.height); // Cropping if (!CGRectIsEmpty(cropRect) && !CGRectEqualToRect(cropRect, CGRectMake(0, 0, 1, 1))) { CGRect innerRect = CGRectMake(floorf(src.size.width * cropRect.origin.x), floorf(src.size.height * cropRect.origin.y), floorf(src.size.width * cropRect.size.width), floorf(src.size.height * cropRect.size.height)); // Create a new image containing only the cropped inner rect. srcImageRef = CGImageCreateWithImageInRect(srcImageRef, innerRect); croppedImageRef = srcImageRef; // This new image will likely have a different width and height, so we have to update // the source rect as a result. srcRect = CGRectMake(0, 0, CGRectGetWidth(innerRect), CGRectGetHeight(innerRect)); } // Display if (0 < displaySize.width && 0 < displaySize.height) { if ((NINetworkImageViewScaleToFillLeavesExcess == (NINetworkImageViewScaleToFillLeavesExcess & scaleOptions)) && UIViewContentModeScaleAspectFill == contentMode) { // Make the display size match the aspect ratio of the source image by growing the // display size. CGFloat imageAspectRatio = srcRect.size.width / srcRect.size.height; CGFloat displayAspectRatio = displaySize.width / displaySize.height; if (imageAspectRatio > displayAspectRatio) { // The image is wider than the display, so let's increase the width. displaySize.width = displaySize.height * imageAspectRatio; } else if (imageAspectRatio < displayAspectRatio) { // The image is taller than the display, so let's increase the height. displaySize.height = displaySize.width * (srcRect.size.height / srcRect.size.width); } } else if ((NINetworkImageViewScaleToFitCropsExcess == (NINetworkImageViewScaleToFitCropsExcess & scaleOptions)) && UIViewContentModeScaleAspectFit == contentMode) { // Make the display size match the aspect ratio of the source image by shrinking the // display size. CGFloat imageAspectRatio = srcRect.size.width / srcRect.size.height; CGFloat displayAspectRatio = displaySize.width / displaySize.height; if (imageAspectRatio > displayAspectRatio) { // The image is wider than the display, so let's decrease the height. displaySize.height = displaySize.width * (srcRect.size.height / srcRect.size.width); } else if (imageAspectRatio < displayAspectRatio) { // The image is taller than the display, so let's decrease the width. displaySize.width = displaySize.height * imageAspectRatio; } } CGRect srcCropRect = [self sourceRectWithImageSize: srcRect.size displaySize: displaySize contentMode: contentMode]; srcCropRect = CGRectMake(floorf(srcCropRect.origin.x), floorf(srcCropRect.origin.y), roundf(srcCropRect.size.width), roundf(srcCropRect.size.height)); // Do we need to crop the source? if (!CGRectEqualToRect(srcCropRect, srcRect)) { srcImageRef = CGImageCreateWithImageInRect(srcImageRef, srcCropRect); trimmedImageRef = srcImageRef; srcRect = CGRectMake(0, 0, CGRectGetWidth(srcCropRect), CGRectGetHeight(srcCropRect)); // Release the cropped image source to reduce this thread's memory consumption. if (nil != croppedImageRef) { CGImageRelease(croppedImageRef); croppedImageRef = nil; } } // Calcuate the destination frame. CGRect dstBlitRect = [self destinationRectWithImageSize: srcRect.size displaySize: displaySize contentMode: contentMode]; dstBlitRect = CGRectMake(floorf(dstBlitRect.origin.x), floorf(dstBlitRect.origin.y), roundf(dstBlitRect.size.width), roundf(dstBlitRect.size.height)); // Round any remainder on the display size dimensions. displaySize = CGSizeMake(roundf(displaySize.width), roundf(displaySize.height)); // See table "Supported Pixel Formats" in the following guide for support iOS bitmap formats: // http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bmi = kCGImageAlphaPremultipliedLast; // For screen sizes with higher resolutions, we create a larger image with a scale value // so that it appears crisper on the screen. CGFloat screenScale = NIScreenScale(); // Create our final composite image. CGContextRef dstBmp = CGBitmapContextCreate(NULL, displaySize.width * screenScale, displaySize.height * screenScale, 8, 0, colorSpace, bmi); // If this fails then we're likely creating an invalid bitmap and shit's about to go down. // In production this will fail somewhat gracefully, in that we'll end up just using the // source image instead of the cropped and resized image. NIDASSERT(nil != dstBmp); if (nil != dstBmp) { CGRect dstRect = CGRectMake(0, 0, displaySize.width * screenScale, displaySize.height * screenScale); // Render the source image into the destination image. CGContextClearRect(dstBmp, dstRect); CGContextSetInterpolationQuality(dstBmp, interpolationQuality); CGRect scaledBlitRect = CGRectMake(dstBlitRect.origin.x * screenScale, dstBlitRect.origin.y * screenScale, dstBlitRect.size.width * screenScale, dstBlitRect.size.height * screenScale); CGContextDrawImage(dstBmp, scaledBlitRect, srcImageRef); CGImageRef resultImageRef = CGBitmapContextCreateImage(dstBmp); if (nil != resultImageRef) { resultImage = [UIImage imageWithCGImage:resultImageRef scale:screenScale orientation:src.imageOrientation]; CGImageRelease(resultImageRef); } CGContextRelease(dstBmp); } CGColorSpaceRelease(colorSpace); } else if (nil != croppedImageRef) { resultImage = [UIImage imageWithCGImage:srcImageRef]; } // Memory cleanup. if (nil != trimmedImageRef) { CGImageRelease(trimmedImageRef); } if (nil != croppedImageRef) { CGImageRelease(croppedImageRef); } return resultImage; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NIImageResponseSerializer.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "AFURLResponseSerialization.h" #import "NINetworkImageView.h" // For NINetworkImageViewScaleOptions. /** * The NIImageResponseSerializer class provides an implementation of the AFNetworking serializer * object for Nimbus network images. * * This object is used internally with NINetworkImageView, though it can be used with custom * AFNetworking implementations. Each of the properties should be respected as per the documentation * in NIImageProcessing. */ @interface NIImageResponseSerializer : AFImageResponseSerializer @property (nonatomic, assign) UIViewContentMode contentMode; @property (nonatomic, assign) CGRect cropRect; @property (nonatomic, assign) CGSize displaySize; @property (nonatomic, assign) NINetworkImageViewScaleOptions scaleOptions; @property (nonatomic, assign) CGInterpolationQuality interpolationQuality; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NIImageResponseSerializer.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIImageResponseSerializer.h" #import "NIImageProcessing.h" @implementation NIImageResponseSerializer - (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error { id responseObject = [super responseObjectForResponse:response data:data error:error]; if (nil != responseObject && [responseObject isKindOfClass:[UIImage class]]) { responseObject = [NIImageProcessing imageFromSource:responseObject withContentMode:self.contentMode cropRect:self.cropRect displaySize:self.displaySize scaleOptions:self.scaleOptions interpolationQuality:self.interpolationQuality]; } return responseObject; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NINetworkImageView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIInMemoryCache.h" #import "NimbusCore.h" @protocol NINetworkImageViewDelegate; @protocol ASICacheDelegate; // See the diskCacheLifetime property for more documentation related to this enumeration. typedef enum { /** * Store images on disk in the session disk cache. Images stored with this lifetime will * be removed when the app starts again or when the session cache is explicitly cleared. */ NINetworkImageViewDiskCacheLifetimeSession, /** * Store images on disk in the permanent disk cache. Images stored with this lifetime will * only be removed when the permanent cache is explicitly cleared. */ NINetworkImageViewDiskCacheLifetimePermanent, } NINetworkImageViewDiskCacheLifetime; typedef enum { NINetworkImageViewScaleToFitLeavesExcessAndScaleToFillCropsExcess = 0x00, NINetworkImageViewScaleToFitCropsExcess = 0x01, NINetworkImageViewScaleToFillLeavesExcess = 0x02, } NINetworkImageViewScaleOptions; /** * A protocol defining the set of characteristics for an operation to be used with * NINetworkImageView. */ @protocol NINetworkImageOperation <NSObject> @required @property (readonly, copy) NSString* cacheIdentifier; @property (assign) CGRect imageCropRect; @property (assign) CGSize imageDisplaySize; @property (assign) NINetworkImageViewScaleOptions scaleOptions; @property (assign) CGInterpolationQuality interpolationQuality; @property (assign) UIViewContentMode imageContentMode; @property (strong) UIImage* imageCroppedAndSizedForDisplay; @end /** * A network-enabled image view that consumes minimal amounts of memory. * * Intelligently crops and resizes images for optimal memory use and uses threads to avoid * processing images on the UI thread. * * @ingroup NimbusNetworkImage */ @interface NINetworkImageView : UIImageView <NIOperationDelegate> #pragma mark Creating a Network Image View - (id)initWithImage:(UIImage *)image; #pragma mark Configurable Presentation Properties @property (nonatomic, strong) UIImage* initialImage; // Default: nil @property (nonatomic, assign) BOOL sizeForDisplay; // Default: YES @property (nonatomic, assign) NINetworkImageViewScaleOptions scaleOptions; // Default: NINetworkImageViewScaleToFitLeavesExcessAndScaleToFillCropsExcess @property (nonatomic, assign) CGInterpolationQuality interpolationQuality; // Default: kCGInterpolationDefault #pragma mark Configurable Properties @property (nonatomic, strong) NIImageMemoryCache* imageMemoryCache; // Default: [Nimbus imageMemoryCache] @property (nonatomic, strong) NSOperationQueue* networkOperationQueue; // Default: [Nimbus networkOperationQueue] @property (nonatomic, assign) NSTimeInterval maxAge; // Default: 0 #pragma mark Requesting a Network Image - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage; - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize; - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode; - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect; - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage cropRect:(CGRect)cropRect; - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage contentMode:(UIViewContentMode)contentMode; - (void)setNetworkImageOperation:(NIOperation<NINetworkImageOperation> *)operation forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect; #pragma mark State @property (nonatomic, readonly, assign, getter=isLoading) BOOL loading; #pragma mark Reusable View - (void)prepareForReuse; #pragma mark Delegation @property (nonatomic, weak) id<NINetworkImageViewDelegate> delegate; #pragma mark Subclassing - (void)networkImageViewDidStartLoading; - (void)networkImageViewDidLoadImage:(UIImage *)image; - (void)networkImageViewDidFailWithError:(NSError *)error; @end /** * The image view delegate used to inform of state changes. * * @ingroup NimbusNetworkImage */ @protocol NINetworkImageViewDelegate <NSObject> @optional /** * The image has begun an asynchronous download of the image. */ - (void)networkImageViewDidStartLoad:(NINetworkImageView *)imageView; /** * The image has completed an asynchronous download of the image. */ - (void)networkImageView:(NINetworkImageView *)imageView didLoadImage:(UIImage *)image; /** * The asynchronous download failed. */ - (void)networkImageView:(NINetworkImageView *)imageView didFailWithError:(NSError *)error; /** * The progress of the download. */ - (void)networkImageView:(NINetworkImageView *)imageView readBytes:(long long)readBytes totalBytes:(long long)totalBytes; @end /** * Flags for modifying the way cropping is handled when scaling images to fit or fill. * * @enum NINetworkImageViewScaleOptions * @ingroup NimbusNetworkImage * * By default the network image view will behave in the following way for these content modes: * * - <b>UIViewContentModeScaleAspectFit</b>: Leaves unfilled space as transparent. * - <b>UIViewContentModeScaleAspectFill</b>: Crops any excess pixels. * * The resulting image size will exactly match the display size. * * You can modify this behavior using the following two flags which should be set using * binary operators. * * @htmlonly * <pre> * NINetworkImageViewScaleToFitCropsRemainder * The final image size will be shrunk to fit the image such that there is no transparency. * * NINetworkImageViewScaleToFillLeavesRemainder * The final image size will be grown to include the excess pixels. * </pre> * @endhtmlonly * * <h1>Examples</h1> * * The following examples use this image: * * @image html clouds500x375.jpeg "Dimensions: 500x375" * * * <h2>Default settings with UIViewContentModeScaleAspectFit</h2> * * <h3>Result image (display size 100x100)</h3> * * @image html clouds100x100-fit.png "Fit image with default settings leaves transparent pixels. Size: 100x100." * * <h3>Example code</h3> * * @code * imageView.scaleOptions = NINetworkImageViewScaleToFitLeavesExcessAndScaleToFillCropsExcess; * * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100) * contentMode: UIViewContentModeScaleAspectFit]; * * source image size: 500x375 [aspect ratio: 1.3333] * display size: 100x100 [aspect ratio: 1] * result image size: 100x100 [aspect ratio: 1] (transparency on the left and right edges) * image blt size: 100x75 [aspect ratio: 1.3333] * @endcode * * * <h2>Default settings with UIViewContentModeScaleAspectFill</h2> * * <h3>Result image (display size 100x100)</h3> * * @image html clouds100x100-fill.png "Fill image with default settings chops excess pixels. Size: 100x100." * * <h3>Example code</h3> * * @code * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100) * contentMode: UIViewContentModeScaleAspectFill]; * * source image size: 500x375 [aspect ratio: 1.3333] * display size: 100x100 [aspect ratio: 1] * result image size: 100x100 [aspect ratio: 1] * image blt size: 133x100 [aspect ratio: 1.3333] * @endcode * * * <h2>NINetworkImageViewScaleToFitCropsExcess with UIViewContentModeScaleAspectFit</h2> * * <h3>Result image (display size 100x100)</h3> * * @image html clouds100x100-fit-cropped.png "Fit image with NINetworkImageViewScaleToFitCropsExcess crops the transparency. Size: 100x75." * * <h3>Example code</h3> * * @code * // Turn on NINetworkImageViewScaleToFitCropsExcess * imageView.scaleOptions |= NINetworkImageViewScaleToFitCropsExcess; * * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100) * contentMode: UIViewContentModeScaleAspectFill]; * * source image size: 500x375 [aspect ratio: 1.3333] * display size: 100x100 [aspect ratio: 1] * result image size: 100x75 [aspect ratio: 1.3333] * image blt size: 100x75 [aspect ratio: 1.3333] * @endcode * * * <h2>NINetworkImageViewScaleToFillLeavesExcess with UIViewContentModeScaleAspectFill</h2> * * <h3>Result image (display size 100x100)</h3> * * @image html clouds100x100-fill-excess.png "Fill image with NINetworkImageViewScaleToFillLeavesExcess leaves the excess. Size: 133x100." * * <h3>Example code</h3> * * @code * // Turn on NINetworkImageViewScaleToFillLeavesExcess * imageView.scaleOptions |= NINetworkImageViewScaleToFillLeavesExcess; * * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100) * contentMode: UIViewContentModeScaleAspectFill]; * * source image size: 500x375 [aspect ratio: 1.3333] * display size: 100x100 [aspect ratio: 1] * result image size: 133x100 [aspect ratio: 1.3333] * image blt size: 133x100 [aspect ratio: 1.3333] * @endcode */ /** * @class NINetworkImageView * * * <h2>Examples</h2> * * <h3>Two basic methods for setting the display size of the network image</h3> * * @code * UIImage* image; // some previously loaded image. * NINetworkImageView* imageView = [[[NINetworkImageView alloc] initWithImage:image] autorelease]; * * // Method #1: Use the image's frame to determine the display size for the network image. * imageView.frame = CGRectMake(0, 0, 100, 100); * [imageView setPathToNetworkImage:@"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg"]; * * // Method #2: use the method setPathToNetworkImage:forDisplaySize: * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100)]; * @endcode * * <i>Code Breakdown</i> * * @code * NINetworkImageView* imageView = [[[NINetworkImageView alloc] initWithImage:image] autorelease]; * @endcode * * Initializes the network image view with a preloaded image, usually a "default" image * to be displayed until the network image downloads. * * @code * imageView.frame = CGRectMake(0, 0, 100, 100); * [imageView setPathToNetworkImage:@"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg"]; * @endcode * * We must take care to set the frame before requesting the network image, otherwise the * image's display size will be 0,0 and the network image won't be cropped or sized to fit. * * @code * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * forDisplaySize: CGSizeMake(100, 100)]; * @endcode * * If you don't want to modify the frame of the image, you can alternatively specify * the display size as a parameter to the setPathToNetworkImage: method. * * * <h3>Use a different contentMode for the network image.</h3> * * @code * UIImage* image; // some previously loaded image. * NINetworkImageView* imageView = [[[NINetworkImageView alloc] initWithImage:image] autorelease]; * * imageView.frame = CGRectMake(0, 0, 100, 100); * imageView.contentMode = UIViewContentModeCenter; // Centers the image in the frame. * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * contentMode: UIViewContentModeScaleAspectFill]; * @endcode * * <i>Code Breakdown</i> * * @code * [imageView setPathToNetworkImage: @"http://farm2.static.flickr.com/1165/644335254_4b8a712be5.jpg" * contentMode: UIViewContentModeScaleAspectFill]; * @endcode * * This means: <i>after the image is downloaded, crop and resize the image with an aspect * fill content mode.</i> * The image returned from the thread will be cropped and sized to fit the imageView perfectly * at the given 100x100 dimensions. * Because imageView has a contentMode of UIViewContentModeCenter, if we were to make the * image view larger the downloaded image would stay in the center of the image view and * leave empty space on all sides. */ /** @name Creating a Network Image View */ /** * Designated initializer. * * @param image This will be the initialImage. * @fn NINetworkImageView::initWithImage: */ /** * @name Configurable Presentation Properties */ /** * The image being displayed while the network image is being fetched. * * This is the same image passed into initWithImage: immediately after initialization. This * is used when preparing this view for reuse. Changing the initial image after creating * the object will only display the new image if the currently displayed image is * is the initial image or nil. * * The initial image is drawn only using the view's contentMode. Cropping and resizing are only * performed on the image fetched from the network. * * @fn NINetworkImageView::initialImage */ /** * A flag for enabling the resizing of images for display. * * When enabled, the downloaded image will be resized to fit the dimensions of the image view * using the image view's content mode. * * When disabled, the full image is drawn as-is. This is generally much less efficient when * working with large photos and will also increase the memory footprint. * * If your images are pre-cropped and sized then this isn't necessary, but the network image * loader is smart enough to realize this so it's in your best interest to leave this on. * * By default this is YES. * * @fn NINetworkImageView::sizeForDisplay */ /** * Options for modifying the way images are cropped when scaling. * * By default this is NINetworkImageViewScaleToFitLeavesExcessAndScaleToFillCropsExcess. * * @see NINetworkImageViewScaleOptions * @fn NINetworkImageView::scaleOptions */ /** * The interpolation quality to use when resizing the image. * * The default value is kCGInterpolationDefault. * * @fn NINetworkImageView::interpolationQuality */ /** @name Configurable Properties */ /** * The image memory cache used by this image view to store the image in memory. * * It may be useful to specify your own image memory cache if you have a unique memory requirement * and do not want the image being placed in the global memory cache, potentially pushing out * other images. * * By default this is [Nimbus imageMemoryCache]. * * @attention Setting this to nil will disable the memory cache. This will force the * image view to load the image from the disk cache or network, depending on * what is available. * * @remark If you replace Nimbus' global image memory cache with a new image cache after * creating this image view, this image view will still use the old image cache. * * @see Nimbus::globalImageMemoryCache * @see Nimbus::setGlobalImageMemoryCache: * @fn NINetworkImageView::imageMemoryCache */ /** * The image disk cache used by this image view to store the image on disk. * * After the image has finished downloading we store it in a disk cache to avoid hitting the * network again if we want to load the image later on. * * By default this is [ASIDownloadCache sharedCache]. * * @attention Setting this to nil will disable the disk cache. Images downloaded from the * network will be stored in the memory cache, if available. * * @fn NINetworkImageView::imageMemoryCache */ /** * The network operation queue used by this image view to load the image from network and disk. * * By default this is [Nimbus networkOperationQueue]. * * @attention This property must be non-nil. If you attempt to set it to nil, a debug * assertion will fire and Nimbus' global network operation queue will be set. * * @see Nimbus::globalNetworkOperationQueue * @see Nimbus::setGlobalNetworkOperationQueue: * * @fn NINetworkImageView::networkOperationQueue */ /** * The maximum amount of time that an image will stay in memory after the request completes. * * If this value is non-zero then the respone header's expiration date information will be * ignored in favor of using this value. * * If this value is zero then the response header's max-age value will be used if it exists, * otherwise it will use the Expires value if it exists. * * A negative value will cause this image to NOT be stored in the memory cache. * * By default this is 0. * * @fn NINetworkImageView::maxAge */ /** * The lifetime for an image stored in the disk cache. * * You can choose to keep the image around forever (until explicitly deleted) or for the life * of an applicaton's session (when the app starts the next time the cache will be cleared). * * Example: Clearing the session cache. * @code * [imageDiskCache clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy]; * @endcode * * Example: Clearing the permanent cache. * @code * [imageDiskCache clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy]; * @endcode * * By default this is NINetworkImageViewDiskCacheLifetimePermanent. * * @fn NINetworkImageView::diskCacheLifetime */ /** * The last path assigned to the image view. * * This property may be used to avoid setting the network path repeatedly and clobbering * previous requests. * * @note It is debatable whether this has any practical use and is being considered * for removal. * * @fn NINetworkImageView::lastPathToNetworkImage */ /** @name State */ /** * Whether there is an active request for this image view. * * If there is currently an image being fetched then this will be YES. * * @fn NINetworkImageView::isLoading */ /** @name Delegation */ /** * Delegate for state change notifications. * * @fn NINetworkImageView::delegate */ /** @name Reusable View */ /** * Kill any network requests and replace the displayed image with the initial image. * * Prepares this view for reuse by cancelling any existing requests and displaying the * initial image again. * * @fn NINetworkImageView::prepareForReuse */ /** * @name Requesting a Network Image */ /** * Load an image from the network using the current frame as the display size. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * Uses self.contentMode to crop and resize the image. * * The image's current frame will be used as the display size for the image. * * @param pathToNetworkImage The network path to the image to be displayed. * @fn NINetworkImageView::setPathToNetworkImage: */ /** * Load an image from the network with a specific display size. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * Uses self.contentMode to crop and resize the image. * * @param pathToNetworkImage The network path to the image to be displayed. * @param displaySize Used instead of the image's frame to determine the display size. * @fn NINetworkImageView::setPathToNetworkImage:forDisplaySize: */ /** * Load an image from the network with a specific display size. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * @param pathToNetworkImage The network path to the image to be displayed. * @param displaySize Used instead of the image's frame to determine the display size. * @param contentMode The content mode used to crop and resize the image. * @fn NINetworkImageView::setPathToNetworkImage:forDisplaySize:contentMode: */ /** * Load an image from the network with a crop rect and the current frame as the display size. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * Uses self.contentMode to crop and resize the image. * * The image's current frame will be used as the display size for the image. * * @param pathToNetworkImage The network path to the image to be displayed. * @param cropRect x/y, width/height are in percent coordinates. * Valid range is [0..1] for all values. * @fn NINetworkImageView::setPathToNetworkImage:cropRect: */ /** * Load an image from the network with a specific display size. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * The image's current frame will be used as the display size for the image. * * @param pathToNetworkImage The network path to the image to be displayed. * @param contentMode The content mode used to crop and resize the image. * @fn NINetworkImageView::setPathToNetworkImage:contentMode: */ /** * Load an image from the network with a specific display size and crop rect. * * Loads the image from the memory cache if possible, otherwise fires off a network request * with this object's network image information. * * @param pathToNetworkImage The network path to the image to be displayed. * @param cropRect x/y, width/height are in percent coordinates. * Valid range is [0..1] for all values. * @param displaySize Used instead of the image's frame to determine the display size. * @param contentMode The content mode used to crop and resize the image. * @fn NINetworkImageView::setPathToNetworkImage:forDisplaySize:contentMode:cropRect: */ /** * @name Subclassing * * The following methods are provided to aid in subclassing and are not meant to be * used externally. */ /** * A network request has begun. * * @fn NINetworkImageView::networkImageViewDidStartLoading */ /** * The image has been loaded, either from the network or in-memory. * * @fn NINetworkImageView::networkImageViewDidLoadImage: */ /** * A network request failed to load. * * @fn NINetworkImageView::networkImageViewDidFailWithError: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NINetworkImageView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 June 15, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NINetworkImageView.h" #import "NimbusCore.h" #import "AFNetworking.h" #import "NIImageProcessing.h" #import "NIImageResponseSerializer.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NINetworkImageView() @property (nonatomic, strong) NSOperation* operation; @end @implementation NINetworkImageView - (void)cancelOperation { if ([self.operation isKindOfClass:[NIOperation class]]) { NIOperation* request = (NIOperation *)self.operation; // Clear the delegate so that we don't receive a didFail notification when we cancel the // operation. request.delegate = nil; } [self.operation cancel]; } - (void)dealloc { [self cancelOperation]; } - (void)assignDefaults { self.sizeForDisplay = YES; self.scaleOptions = NINetworkImageViewScaleToFitLeavesExcessAndScaleToFillCropsExcess; self.interpolationQuality = kCGInterpolationDefault; self.imageMemoryCache = [Nimbus imageMemoryCache]; self.networkOperationQueue = [Nimbus networkOperationQueue]; } - (id)initWithImage:(UIImage *)image { if ((self = [super initWithImage:image])) { [self assignDefaults]; // Retain the initial image. self.initialImage = image; } return self; } - (id)initWithFrame:(CGRect)frame { if ((self = [self initWithImage:nil])) { self.frame = frame; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if ((self = [super initWithCoder:aDecoder])) { if (nil != self.image) { self.initialImage = self.image; } [self assignDefaults]; } return self; } - (id)init { return [self initWithImage:nil]; } - (NSString *)cacheKeyForCacheIdentifier:(NSString *)cacheIdentifier imageSize:(CGSize)imageSize cropRect:(CGRect)cropRect contentMode:(UIViewContentMode)contentMode scaleOptions:(NINetworkImageViewScaleOptions)scaleOptions { NIDASSERT(NIIsStringWithAnyText(cacheIdentifier)); NSString* cacheKey = cacheIdentifier; // Append the size to the key. This allows us to differentiate cache keys by image dimension. // If the display size ever changes, we want to ensure that we're fetching the correct image // from the cache. if (self.sizeForDisplay) { cacheKey = [cacheKey stringByAppendingFormat:@"%@%@{%d,%d}", NSStringFromCGSize(imageSize), NSStringFromCGRect(cropRect), contentMode, scaleOptions]; } // The resulting cache key will look like: // /path/to/image({width,height}{contentMode,cropImageForDisplay}) return cacheKey; } #pragma mark - Internal consistent implementation of state changes - (void)_didStartLoading { if ([self.delegate respondsToSelector:@selector(networkImageViewDidStartLoad:)]) { [self.delegate networkImageViewDidStartLoad:self]; } [self networkImageViewDidStartLoading]; } - (void)_didFinishLoadingWithImage:(UIImage *)image cacheIdentifier:(NSString *)cacheIdentifier displaySize:(CGSize)displaySize cropRect:(CGRect)cropRect contentMode:(UIViewContentMode)contentMode scaleOptions:(NINetworkImageViewScaleOptions)scaleOptions expirationDate:(NSDate *)expirationDate { // Store the result image in the memory cache. if (nil != self.imageMemoryCache && nil != image) { NSString* cacheKey = [self cacheKeyForCacheIdentifier:cacheIdentifier imageSize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:scaleOptions]; // Store the image in the memory cache, possibly with an expiration date. [self.imageMemoryCache storeObject: image withName: cacheKey expiresAfter: expirationDate]; } if (nil != image) { // Display the new image. [self setImage:image]; } else { [self setImage:self.initialImage]; } self.operation = nil; if ([self.delegate respondsToSelector:@selector(networkImageView:didLoadImage:)]) { [self.delegate networkImageView:self didLoadImage:self.image]; } [self networkImageViewDidLoadImage:image]; } - (void)_didFailToLoadWithError:(NSError *)error { self.operation = nil; if ([self.delegate respondsToSelector:@selector(networkImageView:didFailWithError:)]) { [self.delegate networkImageView:self didFailWithError:error]; } [self networkImageViewDidFailWithError:error]; } #pragma mark - NIOperationDelegate - (void)nimbusOperationDidStart:(NIOperation *)operation { [self _didStartLoading]; } - (void)nimbusOperationDidFinish:(NIOperation<NINetworkImageOperation> *)operation { if (operation.isCancelled || operation != self.operation) { return; } [self _didFinishLoadingWithImage:operation.imageCroppedAndSizedForDisplay cacheIdentifier:operation.cacheIdentifier displaySize:operation.imageDisplaySize cropRect:operation.imageCropRect contentMode:operation.imageContentMode scaleOptions:operation.scaleOptions expirationDate:nil]; } - (void)nimbusOperationDidFail:(NIOperation *)operation withError:(NSError *)error { [self _didFailToLoadWithError:error]; } #pragma mark - Subclassing - (void)networkImageViewDidStartLoading { // No-op. Meant to be overridden. } - (void)networkImageViewDidLoadImage:(UIImage *)image { // No-op. Meant to be overridden. } - (void)networkImageViewDidFailWithError:(NSError *)error { // No-op. Meant to be overridden. } #pragma mark - Public - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage { [self setPathToNetworkImage: pathToNetworkImage forDisplaySize: CGSizeZero contentMode: self.contentMode cropRect: CGRectZero]; } - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize { [self setPathToNetworkImage: pathToNetworkImage forDisplaySize: displaySize contentMode: self.contentMode cropRect: CGRectZero]; } - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode { [self setPathToNetworkImage: pathToNetworkImage forDisplaySize: displaySize contentMode: contentMode cropRect: CGRectZero]; } - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage cropRect:(CGRect)cropRect { [self setPathToNetworkImage: pathToNetworkImage forDisplaySize: CGSizeZero contentMode: self.contentMode cropRect: cropRect]; } - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage contentMode:(UIViewContentMode)contentMode { [self setPathToNetworkImage: pathToNetworkImage forDisplaySize: CGSizeZero contentMode: contentMode cropRect: CGRectZero]; } - (void)setPathToNetworkImage:(NSString *)pathToNetworkImage forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect { [self cancelOperation]; if (NIIsStringWithAnyText(pathToNetworkImage)) { NSURL* url = nil; // Check for file URLs. if ([pathToNetworkImage hasPrefix:@"/"]) { // If the url starts with / then it's likely a file URL, so treat it accordingly. url = [NSURL fileURLWithPath:pathToNetworkImage]; } else { // Otherwise we assume it's a regular URL. url = [NSURL URLWithString:[pathToNetworkImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; } // If the URL failed to be created, there's not much we can do here. if (nil == url) { return; } // We explicitly do not allow negative display sizes. Check the call stack to figure // out who is providing a negative display size. It's possible that displaySize is an // uninitialized CGSize structure. NIDASSERT(displaySize.width >= 0); NIDASSERT(displaySize.height >= 0); // If an invalid display size IS provided, use the image view's frame instead. if (0 >= displaySize.width || 0 >= displaySize.height) { displaySize = self.frame.size; } UIImage* image = nil; // Attempt to load the image from memory first. NSString* cacheKey = nil; if (nil != self.imageMemoryCache) { cacheKey = [self cacheKeyForCacheIdentifier:pathToNetworkImage imageSize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:self.scaleOptions]; image = [self.imageMemoryCache objectWithName:cacheKey]; } if (nil != image) { // We successfully loaded the image from memory. [self setImage:image]; if ([self.delegate respondsToSelector:@selector(networkImageView:didLoadImage:)]) { [self.delegate networkImageView:self didLoadImage:self.image]; } [self networkImageViewDidLoadImage:image]; } else { if (!self.sizeForDisplay) { displaySize = CGSizeZero; contentMode = UIViewContentModeScaleToFill; } NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation* requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; NIImageResponseSerializer* serializer = [NIImageResponseSerializer serializer]; // We handle image scaling ourselves in the image processing method, so we need to disable // AFNetworking from doing so as well. serializer.imageScale = 1; serializer.contentMode = contentMode; serializer.cropRect = cropRect; serializer.displaySize = displaySize; serializer.scaleOptions = self.scaleOptions; serializer.interpolationQuality = self.interpolationQuality; requestOperation.responseSerializer = serializer; NSString* originalCacheKey = [self cacheKeyForCacheIdentifier:pathToNetworkImage imageSize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:self.scaleOptions]; requestOperation.userInfo = @{@"cacheKey":originalCacheKey}; [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSString* cacheKey = [self cacheKeyForCacheIdentifier:pathToNetworkImage imageSize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:self.scaleOptions]; // Only keep this result if it's for the most recent request. if ([cacheKey isEqualToString:operation.userInfo[@"cacheKey"]]) { [self _didFinishLoadingWithImage:responseObject cacheIdentifier:pathToNetworkImage displaySize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:self.scaleOptions expirationDate:nil]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [self _didFailToLoadWithError:error]; }]; [requestOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { if ([self.delegate respondsToSelector:@selector(networkImageView:readBytes:totalBytes:)]) { [self.delegate networkImageView:self readBytes:totalBytesRead totalBytes:totalBytesExpectedToRead]; } }]; self.operation = requestOperation; [self _didStartLoading]; [self.networkOperationQueue addOperation:requestOperation]; } } } - (void)setNetworkImageOperation:(NIOperation<NINetworkImageOperation> *)operation forDisplaySize:(CGSize)displaySize contentMode:(UIViewContentMode)contentMode cropRect:(CGRect)cropRect { [self cancelOperation]; if (nil != operation) { // We explicitly do not allow negative display sizes. Check the call stack to figure // out who is providing a negative display size. It's possible that displaySize is an // uninitialized CGSize structure. NIDASSERT(displaySize.width >= 0); NIDASSERT(displaySize.height >= 0); // If an invalid display size IS provided, use the image view's frame instead. if (0 >= displaySize.width || 0 >= displaySize.height) { displaySize = self.frame.size; } UIImage* image = nil; // Attempt to load the image from memory first. if (nil != self.imageMemoryCache) { NSString* cacheKey = [self cacheKeyForCacheIdentifier:operation.cacheIdentifier imageSize:displaySize cropRect:cropRect contentMode:contentMode scaleOptions:self.scaleOptions]; image = [self.imageMemoryCache objectWithName:cacheKey]; } if (nil != image) { // We successfully loaded the image from memory. [self setImage:image]; if ([self.delegate respondsToSelector:@selector(networkImageView:didLoadImage:)]) { [self.delegate networkImageView:self didLoadImage:self.image]; } [self networkImageViewDidLoadImage:image]; } else { // Unable to load the image from memory, so let's fire off the operation now. operation.delegate = self; operation.imageCropRect = cropRect; operation.scaleOptions = self.scaleOptions; operation.interpolationQuality = self.interpolationQuality; if (self.sizeForDisplay) { operation.imageDisplaySize = displaySize; operation.imageContentMode = contentMode; } self.operation = operation; [self.networkOperationQueue addOperation:self.operation]; } } } - (void)prepareForReuse { [self cancelOperation]; [self setImage:self.initialImage]; } #pragma mark - Properties - (void)setInitialImage:(UIImage *)initialImage { if (_initialImage != initialImage) { // Only update the displayed image if we're currently showing the old initial image. BOOL updateDisplayedImage = (_initialImage == self.image); _initialImage = initialImage; if (updateDisplayedImage) { [self setImage:_initialImage]; } } } - (BOOL)isLoading { return [self.operation isExecuting]; } - (void)setNetworkOperationQueue:(NSOperationQueue *)queue { // Don't allow a nil network operation queue. NIDASSERT(nil != queue); if (nil == queue) { queue = [Nimbus networkOperationQueue]; } _networkOperationQueue = queue; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/networkimage/src/NimbusNetworkImage.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusNetworkImage Nimbus Network Image * @{ * * <div id="github" feature="networkimage"></div> * * Image views that load images from the network and efficiently store the result in memory and on * disk. * * @image html NINetworkImageViewExample1.png "The various available content modes." * * <h2>Minimum Requirements</h2> * * Required frameworks: * * - UIKit.framework * - CoreText.framework * - AFNetworking https://github.com/AFNetworking/AFNetworking * * Minimum Operating System: <b>iOS 4.0</b> * * Source located in <code>src/networkimage/src</code> * * Presented below is an architectural overview of the Nimbus network image library. * * @image html NINetworkImageDesign1.png "NINetworkImage Design" * * -# To begin using a network image view, simply create an instance of an NINetworkImageView * and use it as you would a UIImageView. The initial image you assign to the view will be * used as the "loading" image and must be a locally accessible image. Note that this * image will not be cropped and resized in any way, so you should take care to crop and * resize it beforehand as necessary. * -# Once you have created your network image view and assigned the initial image, the next step * is to load the network image. Call any of the @link NINetworkImageView::setPathToNetworkImage: setPathToNetworkImage@endlink methods to fire * off a network request for the image on a separate thread. * -# A new NINetworkImageRequest thread will spin off and initiate the request to the network. * -# Once the image has been retrieved from the net, the thread crops and resizes the image * depending on the presentation configurations specified by the image view. In this example, * @link NINetworkImageView::sizeForDisplay sizeForDisplay@endlink and * @link NINetworkImageView::cropImageForDisplay cropImageForDisplay@endlink are enabled. * In this step the image is resized to fit the aspect ratio of the display size. * -# We then crop the image to fit the display frame. * -# Upon completion of all image modifications, we complete the request and return only the * modified image to the image view. This helps to reduce memory usage. * -# The resized and cropped image is then stored in the in-memory image cache for quick access * in the future. * -# At last, the image view sets the new image and displays it. * */ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NimbusCore.h" #import "NIImageProcessing.h" #import "NINetworkImageView.h" /**@}*/
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIDeviceInfo.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> /** * Formats a number of bytes in a human-readable format. * * Will create a string showing the size in bytes, KBs, MBs, or GBs. */ NSString* NIStringFromBytes(unsigned long long bytes); /** * An interface for accessing device information. * * @ingroup Overview-Sensors * * This class is not meant to be instantiated. All methods are class implementations. * * This class aims to simplify the interface for collecting device information. The low-level * mach APIs provide a host of valuable information but it's often in formats that aren't * particularly ready for presentation. * * @attention When using this class on the simulator, the values returned will reflect * those of the computer within which you're running the simulator, not the * simulated device. This is because the simulator is a first-class citizen * on the computer and has full access to your RAM and disk space. */ @interface NIDeviceInfo : NSObject #pragma mark Memory /** @name Memory */ /** * The number of bytes in memory that are free. * * Calculated using the number of free pages of memory. */ + (unsigned long long)bytesOfFreeMemory; /** * The total number of bytes of memory. * * Calculated by adding together the number of free, wired, active, and inactive pages of memory. * * This value may change over time on the device due to the way iOS partitions available memory * for applications. */ + (unsigned long long)bytesOfTotalMemory; /** * Simulate low memory warning * * Don't use this in production because it uses private API */ + (void)simulateLowMemoryWarning; #pragma mark Disk Space /** @name Disk Space */ /** * The number of bytes free on disk. */ + (unsigned long long)bytesOfFreeDiskSpace; /** * The total number of bytes of disk space. */ + (unsigned long long)bytesOfTotalDiskSpace; #pragma mark Battery /** @name Battery */ /** * The battery charge level in the range 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown. * * This is a thin wrapper for [[UIDevice currentDevice] batteryLevel]. */ + (CGFloat)batteryLevel; /** * The current battery state. * * This is a thin wrapper for [[UIDevice currentDevice] batteryState]. */ + (UIDeviceBatteryState)batteryState; #pragma mark Caching /** @name Caching */ /** * Fetches the device's current information and then caches it. * * All subsequent calls to NIDeviceInfo methods will use this cached information. * * This can be a useful way to freeze the device info at a moment in time. * * Example: * * @code * [NIDeviceInfo beginCachedDeviceInfo]; * * // All calls to NIDeviceInfo methods here will use the information retrieved when * // beginCachedDeviceInfo was called. * * [NIDeviceInfo endCachedDeviceInfo]; * @endcode */ + (BOOL)beginCachedDeviceInfo; /** * Stop using the cache for the device info methods. */ + (void)endCachedDeviceInfo; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIDeviceInfo.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIDeviceInfo.h" #import "NimbusCore.h" #import <mach/mach.h> #import <mach/mach_host.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif // Static local state. static BOOL sIsCaching = NO; static BOOL sLastUpdateResult = NO; static vm_size_t sPageSize = 0; static vm_statistics_data_t sVMStats; static NSDictionary* sFileSystem = nil; NSString* NIStringFromBytes(unsigned long long bytes) { static const void* sOrdersOfMagnitude[] = { @"bytes", @"KB", @"MB", @"GB" }; // Determine what magnitude the number of bytes is by shifting off 10 bits at a time // (equivalent to dividing by 1024). unsigned long magnitude = 0; unsigned long long highbits = bytes; unsigned long long inverseBits = ~((unsigned long long)0x3FF); while ((highbits & inverseBits) && magnitude + 1 < (sizeof(sOrdersOfMagnitude) / sizeof(void *))) { // Shift off an order of magnitude. highbits >>= 10; magnitude++; } if (magnitude > 0) { unsigned long long dividend = 1024 << (magnitude - 1) * 10; double result = ((double)bytes / (double)(dividend)); return [NSString stringWithFormat:@"%.2f %@", result, sOrdersOfMagnitude[magnitude]]; } else { // We don't need to bother with dividing bytes. return [NSString stringWithFormat:@"%lld %@", bytes, sOrdersOfMagnitude[magnitude]]; } } @implementation NIDeviceInfo + (void)initialize { [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; memset(&sVMStats, 0, sizeof(sVMStats)); } + (BOOL)updateHostStatistics { mach_port_t host_port = mach_host_self(); mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); host_page_size(host_port, &sPageSize); return (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&sVMStats, &host_size) == KERN_SUCCESS); } + (BOOL)updateFileSystemAttributes { NSError* error = nil; // This path could be any path that is on the device's local disk. NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // Fetch the file system information based on the path given (the user's documents directory). sFileSystem = [[NSFileManager defaultManager] attributesOfFileSystemForPath: [paths lastObject] error: &error]; return (nil == error); } #pragma mark - Public + (unsigned long long)bytesOfFreeMemory { if (!sIsCaching && ![self updateHostStatistics]) { return 0; } unsigned long long mem_free = ((unsigned long long)sVMStats.free_count * (unsigned long long)sPageSize); return mem_free; } + (unsigned long long)bytesOfTotalMemory { if (!sIsCaching && ![self updateHostStatistics]) { return 0; } unsigned long long mem_free = (((unsigned long long)sVMStats.free_count + (unsigned long long)sVMStats.active_count + (unsigned long long)sVMStats.inactive_count + (unsigned long long)sVMStats.wire_count) * (unsigned long long)sPageSize); return mem_free; } + (void)simulateLowMemoryWarning { SEL memoryWarningSel = NSSelectorFromString(@"_performMemoryWarning"); if ([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) { NIDINFO(@"Simulate low memory warning"); // Supress the warning. -Wundeclared-selector was used while ARC is enabled. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [[UIApplication sharedApplication] performSelector:memoryWarningSel]; #pragma clang diagnostic pop } else { // UIApplication no loger responds to _performMemoryWarning exit(1); } } + (unsigned long long)bytesOfFreeDiskSpace { if (!sIsCaching && ![self updateFileSystemAttributes]) { return 0; } unsigned long long bytes = 0; NSNumber* number = [sFileSystem objectForKey:NSFileSystemFreeSize]; bytes = [number unsignedLongLongValue]; return bytes; } + (unsigned long long)bytesOfTotalDiskSpace { if (!sIsCaching && ![self updateFileSystemAttributes]) { return 0; } unsigned long long bytes = 0; NSNumber* number = [sFileSystem objectForKey:NSFileSystemSize]; bytes = [number unsignedLongLongValue]; return bytes; } + (CGFloat)batteryLevel { return [[UIDevice currentDevice] batteryLevel]; } + (UIDeviceBatteryState)batteryState { return [[UIDevice currentDevice] batteryState]; } #pragma mark - Caching + (BOOL)beginCachedDeviceInfo { if (!sIsCaching) { sIsCaching = YES; sLastUpdateResult = [self updateHostStatistics]; sLastUpdateResult = ([self updateFileSystemAttributes] && sLastUpdateResult); } return sLastUpdateResult; } + (void)endCachedDeviceInfo { sIsCaching = NO; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverview.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class NIOverviewView; @class NIOverviewLogger; /** * The Overview state management class. * * @ingroup Overview * * <h2>What is the Overview?</h2> * * The Overview is a paged view that sits directly below the status bar and presents information * about the device and the currently running application. The Overview is extensible, in that * you can write your own pages and add them to the Overview. The included pages allow you to * see the current and historical state of memory and disk use, the console logs, and important * events that have occurred (such as memory warnings). * * * <h2>Before Using the Overview</h2> * * None of the Overview methods will do anything unless you have the DEBUG preprocessor * macro defined. This is by design. The Overview swizzles private API methods in order to * trick the device into showing the Overview as part of the status bar. * * DO *NOT* SUBMIT YOUR APP TO THE APP STORE WITH DEBUG DEFINED. * * If you submit your app to the App Store with DEBUG defined, you *will* be rejected. * Overview works only because it hacks certain aspects of the device using private APIs * and method swizzling. For good reason, Apple will not look too kindly to the Overview * being included in production code. If Apple ever changes any of the APIs that * the Overview depends on then the Overview would break. */ @interface NIOverview : NSObject #pragma mark Initializing the Overview /** @name Initializing the Overview */ /** * Call this immediately in application:didFinishLaunchingWithOptions:. * * This method calls applicationDidFinishLaunchingWithStatusBarHeightOverride: with * |overrideStatusBarHeight| set to NO. */ + (void)applicationDidFinishLaunching; /** * Call this immediately in application:didFinishLaunchingWithOptions:. * * Swizzles the necessary methods for adding the Overview to the view hierarchy and registers * notifications for device state changes if |overrideStatusBarHeight| is true. */ + (void)applicationDidFinishLaunchingWithStatusBarHeightOverride:(BOOL)overrideStatusBarHeight; /** * Adds the Overview to the given window. * * This methods calls addOverviewToWindow:enableDraggingVertically: with |enableDraggingVertically| * set to NO. */ + (void)addOverviewToWindow:(UIWindow *)window; /** * Adds the Overview to the given window. * * The Overview will always be fixed at the top of the device's screen directly * beneath the status bar (if it is visible) if enableDraggingVertically is false. Otherwise, * the overview can be drag vertically. */ + (void)addOverviewToWindow:(UIWindow *)window enableDraggingVertically:(BOOL)enableDraggingVertically; #pragma mark Accessing State Information /** @name Accessing State Information */ /** * The height of the Overview. */ + (CGFloat)height; /** * The frame of the Overview. */ + (CGRect)frame; /** * The Overview view. */ + (NIOverviewView *)view; /** * The Overview logger. * * This is the logger that all of the Overview pages use to present their information. */ + (NIOverviewLogger *)logger; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverview.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverview.h" #if defined(DEBUG) || defined(NI_DEBUG) #import "NIDeviceInfo.h" #import "NIOverviewView.h" #import "NIOverviewPageView.h" #import "NIOverviewSwizzling.h" #import "NIOverviewLogger.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif // Static state. static CGFloat sOverviewHeight = 60; static BOOL sOverviewIsAwake = NO; static BOOL sOverviewHasOverridenStatusBarHeight = NO; static NIOverviewView* sOverviewView = nil; #pragma mark - Logging /** * @internal * * An undocumented method that replaces the default logging mechanism with a custom implementation. * * Your method prototype should look like this: * * void logger(const char *message, unsigned length, BOOL withSyslogBanner) * * @attention This method is undocumented, unsupported, and unlikely to be around * forever. Don't go using it in production code. * * Source: http://support.apple.com/kb/TA45403?viewlocale=en_US */ extern void _NSSetLogCStringFunction(void(*)(const char *, unsigned, BOOL)); void NIOverviewLogMethod(const char* message, unsigned length, BOOL withSyslogBanner); /** * Pipes NSLog messages to the Overview and stderr. * * This method is passed as an argument to _NSSetLogCStringFunction to pipe all NSLog * messages through here. */ void NIOverviewLogMethod(const char* message, unsigned length, BOOL withSyslogBanner) { static NSDateFormatter* formatter = nil; if (nil == formatter) { formatter = [[NSDateFormatter alloc] init]; [formatter setTimeStyle:NSDateFormatterMediumStyle]; [formatter setDateStyle:NSDateFormatterMediumStyle]; } // Don't autorelease here in an attempt to minimize autorelease thrashing in tight // loops. NSString* formattedLogMessage = [[NSString alloc] initWithCString: message encoding: NSUTF8StringEncoding]; dispatch_async(dispatch_get_main_queue(), ^{ NIOverviewConsoleLogEntry* entry = [[NIOverviewConsoleLogEntry alloc] initWithLog:formattedLogMessage]; [[NIOverview logger] addConsoleLog:entry]; }); formattedLogMessage = [[NSString alloc] initWithFormat: @"%@: %s\n", [formatter stringFromDate:[NSDate date]], message]; fprintf(stderr, "%s", [formattedLogMessage UTF8String]); } #endif @implementation NIOverview #pragma mark - Device Orientation Changes #if defined(DEBUG) || defined(NI_DEBUG) + (void)didChangeOrientation { static UIDeviceOrientation lastOrientation = UIDeviceOrientationUnknown; // Don't animate the overview if the device didn't actually change orientations. if (lastOrientation != [[UIDevice currentDevice] orientation] && [[UIDevice currentDevice] orientation] != UIDeviceOrientationUnknown && [[UIDevice currentDevice] orientation] != UIDeviceOrientationFaceUp && [[UIDevice currentDevice] orientation] != UIDeviceOrientationFaceDown) { // When we flip from landscape to landscape or portait to portait the animation lasts // twice as long. UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation]; BOOL isLongAnimation = (UIDeviceOrientationIsLandscape(lastOrientation) == UIDeviceOrientationIsLandscape(currentOrientation)); lastOrientation = currentOrientation; // Hide the overview right away, we'll make it fade back in when the rotation is // finished. sOverviewView.hidden = YES; // Delay showing the overview again until the rotation finishes. [self cancelPreviousPerformRequestsWithTarget:self]; [self performSelector:@selector(showoverviewAfterRotation) withObject:nil afterDelay:NIDeviceRotationDuration(isLongAnimation)]; } } + (void)statusBarWillChangeFrame { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:NIStatusBarBoundsChangeAnimationDuration()]; [UIView setAnimationCurve:NIStatusBarBoundsChangeAnimationCurve()]; CGRect frame = [NIOverview frame]; sOverviewView.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)); [UIView commitAnimations]; } + (void)showoverviewAfterRotation { // Don't modify the overview's frame directly, just modify the transform/center/bounds // properties so that the view is rotated with the device. sOverviewView.transform = NIRotateTransformForOrientation(NIInterfaceOrientation()); // Fetch the frame only to calculate the center. CGRect frame = [NIOverview frame]; sOverviewView.center = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame)); CGRect bounds = sOverviewView.bounds; if (UIInterfaceOrientationIsLandscape(NIInterfaceOrientation())) { bounds.size.width = frame.size.height; bounds.size.height = frame.size.width; } else { bounds.size = frame.size; } sOverviewView.bounds = bounds; // Get ready to fade the overview back in. sOverviewView.hidden = NO; sOverviewView.alpha = 0; [sOverviewView flashScrollIndicators]; // Fade! [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.2]; sOverviewView.alpha = 1; [UIView commitAnimations]; } + (void)didReceiveMemoryWarning { [[NIOverview logger] addEventLog: [[NIOverviewEventLogEntry alloc] initWithType:NIOverviewEventDidReceiveMemoryWarning]]; } #endif #pragma mark - Public + (void)applicationDidFinishLaunching { #if defined(DEBUG) || defined(NI_DEBUG) [self applicationDidFinishLaunchingWithStatusBarHeightOverride:YES]; #endif } + (void)applicationDidFinishLaunchingWithStatusBarHeightOverride:(BOOL)overrideStatusBarHeight { #if defined(DEBUG) || defined(NI_DEBUG) if (!sOverviewIsAwake) { sOverviewIsAwake = YES; sOverviewHasOverridenStatusBarHeight = overrideStatusBarHeight; // Set up the logger right away so that all calls to NSLog will be captured by the // overview. _NSSetLogCStringFunction(NIOverviewLogMethod); if (overrideStatusBarHeight) { NIOverviewSwizzleMethods(); } [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(didChangeOrientation) name: UIDeviceOrientationDidChangeNotification object: nil]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(statusBarWillChangeFrame) name: UIApplicationWillChangeStatusBarFrameNotification object: nil]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(didReceiveMemoryWarning) name: UIApplicationDidReceiveMemoryWarningNotification object: nil]; } #endif } + (void)addOverviewToWindow:(UIWindow *)window { #if defined(DEBUG) || defined(NI_DEBUG) [self addOverviewToWindow:window enableDraggingVertically:NO]; #endif } + (void)addOverviewToWindow:(UIWindow *)window enableDraggingVertically:(BOOL)enableDraggingVertically { #if defined(DEBUG) || defined(NI_DEBUG) if (nil != sOverviewView) { // Remove the old overview in case this gets called multiple times (not sure why you would // though). [sOverviewView removeFromSuperview]; } sOverviewView = [[NIOverviewView alloc] initWithFrame:[self frame]]; [sOverviewView setEnableDraggingVertically:enableDraggingVertically]; [sOverviewView addPageView:[NIInspectionOverviewPageView page]]; [sOverviewView addPageView:[NIOverviewMemoryPageView page]]; [sOverviewView addPageView:[NIOverviewDiskPageView page]]; [sOverviewView addPageView:[NIOverviewMemoryCachePageView page]]; [sOverviewView addPageView:[NIOverviewConsoleLogPageView page]]; [sOverviewView addPageView:[NIOverviewMaxLogLevelPageView page]]; // Hide the view initially because the initial frame will be wrong when the device // starts the app in any orientation other than portrait. Don't worry, we'll fade the // view in once we get our first device notification. sOverviewView.hidden = YES; [window addSubview:sOverviewView]; NSLog(@"The overview has been added to a window."); #endif } + (NIOverviewLogger *)logger { #if defined(DEBUG) || defined(NI_DEBUG) return [NIOverviewLogger sharedLogger]; #else return nil; #endif } + (CGFloat)height { #if defined(DEBUG) || defined(NI_DEBUG) return sOverviewHeight; #else return 0; #endif } + (CGRect)frame { #if defined(DEBUG) || defined(NI_DEBUG) UIInterfaceOrientation orient = NIInterfaceOrientation(); CGFloat overviewWidth; CGRect frame; CGFloat overviewHeight = sOverviewHasOverridenStatusBarHeight ? NIOverviewStatusBarHeight() : NIStatusBarHeight(); // We can't take advantage of automatic view positioning because the overview exists // at the topmost view level (even above the root view controller). As such, we have to // calculate the frame depending on the interface orientation. if (orient == UIInterfaceOrientationLandscapeLeft) { overviewWidth = [UIScreen mainScreen].bounds.size.height; frame = CGRectMake(overviewHeight, 0, sOverviewHeight, overviewWidth); } else if (orient == UIInterfaceOrientationLandscapeRight) { overviewWidth = [UIScreen mainScreen].bounds.size.height; frame = CGRectMake([UIScreen mainScreen].bounds.size.width - (overviewHeight + sOverviewHeight), 0, sOverviewHeight, overviewWidth); } else if (orient == UIInterfaceOrientationPortraitUpsideDown) { overviewWidth = [UIScreen mainScreen].bounds.size.width; frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - (overviewHeight + sOverviewHeight), overviewWidth, sOverviewHeight); } else if (orient == UIInterfaceOrientationPortrait) { overviewWidth = [UIScreen mainScreen].bounds.size.width; frame = CGRectMake(0, overviewHeight, overviewWidth, sOverviewHeight); } else { overviewWidth = [UIScreen mainScreen].bounds.size.width; frame = CGRectMake(0, overviewHeight, overviewWidth, sOverviewHeight); } if ([[UIApplication sharedApplication] isStatusBarHidden]) { // When the status bar is hidden we want to position the overview offscreen. switch (orient) { case UIInterfaceOrientationLandscapeLeft: { frame = CGRectOffset(frame, -frame.size.width, 0); break; } case UIInterfaceOrientationLandscapeRight: { frame = CGRectOffset(frame, frame.size.width, 0); break; } case UIInterfaceOrientationPortrait: { frame = CGRectOffset(frame, 0, -frame.size.height); break; } case UIInterfaceOrientationPortraitUpsideDown: { frame = CGRectOffset(frame, 0, frame.size.height); break; } } } return frame; #else return CGRectZero; #endif } + (UIView *)view { #if defined(DEBUG) || defined(NI_DEBUG) return sOverviewView; #else return nil; #endif } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewGraphView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for weak */ @protocol NIOverviewGraphViewDataSource; /** * A graph view. * * @ingroup Overview-Pages */ @interface NIOverviewGraphView : UIView /** * The data source for this graph view. */ @property (nonatomic, weak) id<NIOverviewGraphViewDataSource> dataSource; @end /** * The data source for NIOverviewGraphView. * * @ingroup Overview-Pages */ @protocol NIOverviewGraphViewDataSource <NSObject> @required /** * Fetches the total range of all x values for this graph. */ - (CGFloat)graphViewXRange:(NIOverviewGraphView *)graphView; /** * Fetches the total range of all y values for this graph. */ - (CGFloat)graphViewYRange:(NIOverviewGraphView *)graphView; /** * The data source should reset its iterator for fetching points in the graph. */ - (void)resetPointIterator; /** * Fetches the next point in the graph to plot. */ - (BOOL)nextPointInGraphView: (NIOverviewGraphView *)graphView point: (CGPoint *)point; /** * The data source should reset its iterator for fetching events in the graph. */ - (void)resetEventIterator; /** * Fetches the next event in the graph to plot. */ - (BOOL)nextEventInGraphView: (NIOverviewGraphView *)graphView xValue: (CGFloat *)xValue color: (UIColor **)color; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewGraphView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewGraphView.h" #import <QuartzCore/QuartzCore.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIOverviewGraphView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.opaque = NO; self.layer.borderWidth = 1; self.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.2f].CGColor; } return self; } - (void)drawGraphWithContext:(CGContextRef)context { CGSize contentSize = self.bounds.size; CGFloat xRange = [self.dataSource graphViewXRange:self]; CGFloat yRange = [self.dataSource graphViewYRange:self]; if (xRange == 0 || yRange == 0) { return; } [self.dataSource resetPointIterator]; CGContextSetLineWidth(context, 1); CGContextSetShouldAntialias(context, YES); BOOL isFirstPoint = YES; CGPoint point = CGPointZero; while ([self.dataSource nextPointInGraphView:self point:&point]) { CGPoint scaledPoint = CGPointMake(point.x / xRange, point.y / yRange); CGPoint plotPoint = CGPointMake(floorf(scaledPoint.x * contentSize.width) - 0.5f, contentSize.height - floorf((scaledPoint.y * 0.8f + 0.1f) * contentSize.height) - 0.5f); if (!isFirstPoint) { CGContextAddLineToPoint(context, plotPoint.x, plotPoint.y); } CGContextMoveToPoint(context, plotPoint.x, plotPoint.y); isFirstPoint = NO; } CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:1 alpha:0.6f].CGColor); CGContextStrokePath(context); [self.dataSource resetEventIterator]; CGFloat xValue = 0; UIColor* color = nil; while ([self.dataSource nextEventInGraphView:self xValue:&xValue color:&color]) { CGFloat scaledXValue = xValue / xRange; CGFloat plotXValue = floorf(scaledXValue * contentSize.width) - 0.5f; CGContextMoveToPoint(context, plotXValue, 0); CGContextAddLineToPoint(context, plotXValue, contentSize.height); CGContextSetStrokeColorWithColor(context, color.CGColor); CGContextStrokePath(context); } } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGRect bounds = self.bounds; UIGraphicsPushContext(context); [self drawGraphWithContext:context]; CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:1 alpha:0.2f].CGColor); CGContextFillRect(context, bounds); CGGradientRef glossGradient = nil; CGColorSpaceRef colorspace = nil; size_t numberOfLocations = 2; CGFloat locations[2] = { 0.0f, 1.0f }; CGFloat components[8] = { 1.0f, 1.0f, 1.0f, 0.35f, 1.0f, 1.0f, 1.0f, 0.06f }; colorspace = CGColorSpaceCreateDeviceRGB(); glossGradient = CGGradientCreateWithColorComponents(colorspace, components, locations, numberOfLocations); CGPoint topCenter = CGPointMake(CGRectGetMidX(bounds), 0.0f); CGPoint midCenter = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)); CGContextDrawLinearGradient(context, glossGradient, topCenter, midCenter, 0); CGGradientRelease(glossGradient); glossGradient = nil; CGColorSpaceRelease(colorspace); colorspace = nil; UIGraphicsPopContext(); } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewLogger.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> extern NSString* const NIOverviewLoggerDidAddDeviceLog; extern NSString* const NIOverviewLoggerDidAddConsoleLog; extern NSString* const NIOverviewLoggerDidAddEventLog; @class NIOverviewDeviceLogEntry; @class NIOverviewConsoleLogEntry; @class NIOverviewEventLogEntry; /** * The Overview logger. * * @ingroup Overview-Logger * * This object stores all of the historical information used to draw the graphs in the * Overview memory and disk pages, as well as the console log page. * * The primary log should be accessed by calling [NIOverview @link NIOverview::logger logger@endlink]. */ @interface NIOverviewLogger : NSObject #pragma mark Configuration Settings /** @name Configuration Settings */ /** * The oldest age of a memory or disk log entry. * * Log entries older than this number of seconds will be pruned from the log. * * By default this is 1 minute. */ @property (nonatomic, assign) NSTimeInterval oldestLogAge; + (NIOverviewLogger*)sharedLogger; #pragma mark Adding Log Entries /** @name Adding Log Entries */ /** * Add a device log. * * This method will first prune expired entries and then add the new entry to the log. */ - (void)addDeviceLog:(NIOverviewDeviceLogEntry *)logEntry; /** * Add a console log. * * This method will not prune console log entries. */ - (void)addConsoleLog:(NIOverviewConsoleLogEntry *)logEntry; /** * Add a event log. * * This method will first prune expired entries and then add the new entry to the log. */ - (void)addEventLog:(NIOverviewEventLogEntry *)logEntry; #pragma mark Accessing Logs /** @name Accessing Logs */ /** * The linked list of device logs. * * Log entries are in increasing chronological order. */ @property (nonatomic, readonly, strong) NSMutableOrderedSet* deviceLogs; /** * The linked list of console logs. * * Log entries are in increasing chronological order. */ @property (nonatomic, readonly, strong) NSMutableOrderedSet* consoleLogs; /** * The linked list of events. * * Log entries are in increasing chronological order. */ @property (nonatomic, readonly, strong) NSMutableOrderedSet* eventLogs; @end /** * The basic requirements for a log entry. * * @ingroup Overview-Logger-Entries * * A basic log entry need only define a timestamp in order to be particularly useful. */ @interface NIOverviewLogEntry : NSObject #pragma mark Creating an Entry /** @name Creating an Entry */ /** * Designated initializer. */ - (id)initWithTimestamp:(NSDate *)timestamp; #pragma mark Entry Information /** @name Entry Information */ /** * The timestamp for this log entry. */ @property (nonatomic, retain) NSDate* timestamp; @end /** * A device log entry. * * @ingroup Overview-Logger-Entries */ @interface NIOverviewDeviceLogEntry : NIOverviewLogEntry #pragma mark Entry Information /** @name Entry Information */ /** * The number of bytes of free memory. */ @property (nonatomic, assign) unsigned long long bytesOfFreeMemory; /** * The number of bytes of total memory. */ @property (nonatomic, assign) unsigned long long bytesOfTotalMemory; /** * The number of bytes of free disk space. */ @property (nonatomic, assign) unsigned long long bytesOfFreeDiskSpace; /** * The number of bytes of total disk space. */ @property (nonatomic, assign) unsigned long long bytesOfTotalDiskSpace; /** * The battery level. */ @property (nonatomic, assign) CGFloat batteryLevel; /** * The state of the battery. */ @property (nonatomic, assign) UIDeviceBatteryState batteryState; @end /** * A console log entry. * * @ingroup Overview-Logger-Entries */ @interface NIOverviewConsoleLogEntry : NIOverviewLogEntry #pragma mark Creating an Entry /** @name Creating an Entry */ /** * Designated initializer. */ - (id)initWithLog:(NSString *)log; #pragma mark Entry Information /** @name Entry Information */ /** * The text that was written to the console log. */ @property (nonatomic, copy) NSString* log; @end typedef enum { NIOverviewEventDidReceiveMemoryWarning, } NIOverviewEventType; /** * An event log entry. * * @ingroup Overview-Logger-Entries */ @interface NIOverviewEventLogEntry : NIOverviewLogEntry #pragma mark Creating an Entry /** @name Creating an Entry */ /** * Designated initializer. */ - (id)initWithType:(NSInteger)type; #pragma mark Entry Information /** @name Entry Information */ /** * The type of event. */ @property (nonatomic, assign) NSInteger type; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewLogger.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewLogger.h" #import "NIDeviceInfo.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif NSString* const NIOverviewLoggerDidAddDeviceLog = @"NIOverviewLoggerDidAddDeviceLog"; NSString* const NIOverviewLoggerDidAddConsoleLog = @"NIOverviewLoggerDidAddConsoleLog"; NSString* const NIOverviewLoggerDidAddEventLog = @"NIOverviewLoggerDidAddEventLog"; @implementation NIOverviewLogger { NSMutableOrderedSet* _deviceLogs; NSMutableOrderedSet* _consoleLogs; NSMutableOrderedSet* _eventLogs; NSTimeInterval _oldestLogAge; NSTimer* _heartbeatTimer; } + (NIOverviewLogger*)sharedLogger { static dispatch_once_t pred = 0; static NIOverviewLogger* instance = nil; dispatch_once(&pred, ^{ instance = [[NIOverviewLogger alloc] init]; }); return instance; } - (id)init { if ((self = [super init])) { _deviceLogs = [[NSMutableOrderedSet alloc] init]; _consoleLogs = [[NSMutableOrderedSet alloc] init]; _eventLogs = [[NSMutableOrderedSet alloc] init]; _oldestLogAge = 60; _heartbeatTimer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(heartbeat) userInfo: nil repeats: YES]; } return self; } - (void)dealloc { [_heartbeatTimer invalidate]; _heartbeatTimer = nil; } - (void)heartbeat { [NIDeviceInfo beginCachedDeviceInfo]; NIOverviewDeviceLogEntry* logEntry = [[NIOverviewDeviceLogEntry alloc] initWithTimestamp:[NSDate date]]; logEntry.bytesOfTotalDiskSpace = [NIDeviceInfo bytesOfTotalDiskSpace]; logEntry.bytesOfFreeDiskSpace = [NIDeviceInfo bytesOfFreeDiskSpace]; logEntry.bytesOfFreeMemory = [NIDeviceInfo bytesOfFreeMemory]; logEntry.bytesOfTotalMemory = [NIDeviceInfo bytesOfTotalMemory]; logEntry.batteryLevel = [NIDeviceInfo batteryLevel]; logEntry.batteryState = [NIDeviceInfo batteryState]; [NIDeviceInfo endCachedDeviceInfo]; [self addDeviceLog:logEntry]; } - (void)pruneEntriesFromLinkedList:(NSMutableOrderedSet *)ll { NSDate* cutoffDate = [NSDate dateWithTimeIntervalSinceNow:-_oldestLogAge]; while ([[((NIOverviewLogEntry *)[ll firstObject]) timestamp] compare:cutoffDate] == NSOrderedAscending) { [ll removeObjectAtIndex:0]; } } - (void)addDeviceLog:(NIOverviewDeviceLogEntry *)logEntry { [self pruneEntriesFromLinkedList:_deviceLogs]; [_deviceLogs addObject:logEntry]; [[NSNotificationCenter defaultCenter] postNotificationName:NIOverviewLoggerDidAddDeviceLog object:nil userInfo:@{@"entry":logEntry}]; } - (void)addConsoleLog:(NIOverviewConsoleLogEntry *)logEntry { [_consoleLogs addObject:logEntry]; [[NSNotificationCenter defaultCenter] postNotificationName:NIOverviewLoggerDidAddConsoleLog object:nil userInfo:@{@"entry":logEntry}]; } - (void)addEventLog:(NIOverviewEventLogEntry *)logEntry { [self pruneEntriesFromLinkedList:_eventLogs]; [_eventLogs addObject:logEntry]; [[NSNotificationCenter defaultCenter] postNotificationName:NIOverviewLoggerDidAddEventLog object:nil userInfo:@{@"entry":logEntry}]; } @end @implementation NIOverviewLogEntry - (id)initWithTimestamp:(NSDate *)timestamp { if ((self = [super init])) { _timestamp = timestamp; } return self; } @end @implementation NIOverviewDeviceLogEntry @end @implementation NIOverviewConsoleLogEntry - (id)initWithLog:(NSString *)logText { if ((self = [super initWithTimestamp:[NSDate date]])) { _log = [logText copy]; } return self; } @end @implementation NIOverviewEventLogEntry - (id)initWithType:(NSInteger)type { if ((self = [super initWithTimestamp:[NSDate date]])) { _type = type; } return self; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewMemoryCacheController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> @class NIMemoryCache; /** * A view controller that displays the contents of an in-memory cache. * * Requires the [models] feature. * * This controller provides useful debugging insights into the contents of an in-memory cache. * It presents a simple summary of the contents of the cache, followed by a listing of each * object in the cache. * * When the cache is a NIImageMemoryCache, the pixel information will also be displayed in the * summary and each of the images will be displayed. * * @ingroup Overview */ @interface NIOverviewMemoryCacheController : UITableViewController // Designated initializer. - (id)initWithMemoryCache:(NIMemoryCache *)cache; @end /** * Initializes a newly allocated cache controller with the given cache object. * * @fn NIOverviewImageCacheController::initWithMemoryCache: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewMemoryCacheController.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewMemoryCacheController.h" #import "NIDeviceInfo.h" #import "NimbusModels.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NIMemoryCache(Private) @property (nonatomic, strong) NSMutableOrderedSet* lruCacheObjects; @end // Anonymous private category for LRU cache objects. @interface NSObject(Private) - (NSDate *)lastAccessTime; @end @interface NIOverviewMemoryCacheController() @property (nonatomic, readonly, strong) NIMemoryCache* cache; @property (nonatomic, strong) NITableViewModel* model; @end @implementation NIOverviewMemoryCacheController - (void)dealloc { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; } - (id)initWithMemoryCache:(NIMemoryCache *)cache { if ((self = [super initWithStyle:UITableViewStyleGrouped])) { _cache = cache; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver: self selector: @selector(didReceiveMemoryWarning:) name: UIApplicationDidReceiveMemoryWarningNotification object: nil]; UIBarButtonItem* refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(didTapRefreshButton:)]; self.navigationItem.rightBarButtonItem = refreshButton; } return self; } - (id)initWithStyle:(UITableViewStyle)style { return [self initWithMemoryCache:[Nimbus imageMemoryCache]]; } #pragma mark - Model - (void)refreshModel { NSMutableArray* contents = [NSMutableArray array]; NSString* summary = nil; // Display a summary. if ([self.cache isKindOfClass:[NIImageMemoryCache class]]) { NIImageMemoryCache* imageCache = (NIImageMemoryCache *)self.cache; summary = [NSString stringWithFormat: @"Number of images: %d\nNumber of pixels: %@/%@\nStress limit: %@", self.cache.count, NIStringFromBytes(imageCache.numberOfPixels), NIStringFromBytes(imageCache.maxNumberOfPixels), NIStringFromBytes(imageCache.maxNumberOfPixelsUnderStress)]; } else { summary = [NSString stringWithFormat: @"Number of objects: %d", self.cache.count]; } [contents addObject:[NITableViewModelFooter footerWithTitle:summary]]; NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; // We care more about time than date here. [formatter setDateStyle:NSDateFormatterShortStyle]; [formatter setTimeStyle:NSDateFormatterMediumStyle]; // Add each of the cache objects to the model. for (id cacheObject in self.cache.lruCacheObjects) { NSString* name = nil; UIImage* image = nil; NSDate* lastAccessTime = nil; // We're accessing a private object from the core here, so we can't assume that any of // these selectors will be around forever. That being said, we should try to remember to // update this controller if the cache object internals ever change. // If any of these assertions fire it means we've changed the cache object signatures but // haven't gotten around to updating this controller yet. NIDASSERT([cacheObject respondsToSelector:@selector(name)]); if ([cacheObject respondsToSelector:@selector(name)]) { name = [cacheObject performSelector:@selector(name)]; } NIDASSERT([cacheObject respondsToSelector:@selector(object)]); if ([cacheObject respondsToSelector:@selector(object)]) { id object = [cacheObject performSelector:@selector(object)]; if ([object isKindOfClass:[UIImage class]]) { image = object; } } NIDASSERT([cacheObject respondsToSelector:@selector(lastAccessTime)]); if ([cacheObject respondsToSelector:@selector(lastAccessTime)]) { lastAccessTime = [cacheObject performSelector:@selector(lastAccessTime)]; } [contents addObject: [NISubtitleCellObject objectWithTitle:name subtitle:[NSString stringWithFormat: @"Last access: %@", [formatter stringFromDate:lastAccessTime]] image:image]]; } if (0 == self.cache.count) { [contents addObject:[NITitleCellObject objectWithTitle:@"No cache objects"]]; } [contents addObject:[NITableViewModelFooter footerWithTitle: @"The most-recently-used object is here at the bottom"]]; self.model = [[NITableViewModel alloc] initWithSectionedArray:contents delegate:(id)[NICellFactory class]]; self.tableView.dataSource = self.model; [self.tableView reloadData]; } - (void)viewDidLoad { [super viewDidLoad]; [self refreshModel]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return NIIsSupportedOrientation(toInterfaceOrientation); } #endif #pragma mark - Notifications - (void)didReceiveMemoryWarning:(NSNotification *)notification { [self refreshModel]; } #pragma mark - Actions - (void)didTapRefreshButton:(UIBarButtonItem *)button { [self refreshModel]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewPageView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #if defined(DEBUG) || defined(NI_DEBUG) #import "NIOverviewGraphView.h" @class NIMemoryCache; /** * A page in the Overview. * * @ingroup Overview-Pages */ @interface NIOverviewPageView : UIView #pragma mark Creating a Page /** @name Creating a Page */ /** * Returns an autoreleased instance of this view. */ + (NIOverviewPageView *)page; #pragma mark Updating a Page /** @name Updating a Page */ /** * Request that this page update its information. * * Should be implemented by the subclass. The default implementation does nothing. */ - (void)update; #pragma mark Configuring a Page /** @name Configuring a Page */ /** * The title of the page. */ @property (nonatomic, copy) NSString* pageTitle; /** * The following methods are provided to aid in subclassing and are not meant to be * used externally. */ #pragma mark Subclassing /** @name Subclassing */ /** * The title label for this page. * * By default this label will be placed flush to the bottom middle of the page. */ @property (nonatomic, readonly, strong) UILabel* titleLabel; /** * Creates a generic label for use in the page. */ - (UILabel *)label; @end /** * A page that renders a graph and two labels. * * @ingroup Overview-Pages */ @interface NIOverviewGraphPageView : NIOverviewPageView < NIOverviewGraphViewDataSource > { @private UILabel* _label1; UILabel* _label2; NIOverviewGraphView* _graphView; NSEnumerator* _eventEnumerator; } @property (nonatomic, readonly, strong) UILabel* label1; @property (nonatomic, readonly, strong) UILabel* label2; @property (nonatomic, readonly, strong) NIOverviewGraphView* graphView; @end /** * A page that renders a graph showing free memory. * * @image html overview-memory1.png "The memory page." * * @ingroup Overview-Pages */ @interface NIOverviewMemoryPageView : NIOverviewGraphPageView { @private NSEnumerator* _enumerator; unsigned long long _minMemory; } @end /** * A page that renders a graph showing free disk space. * * @image html overview-disk1.png "The disk page." * * @ingroup Overview-Pages */ @interface NIOverviewDiskPageView : NIOverviewGraphPageView { @private NSEnumerator* _enumerator; unsigned long long _minDiskUse; } @end /** * A page that shows all of the logs sent to the console. * * @image html overview-log1.png "The log page." * * @ingroup Overview-Pages */ @interface NIOverviewConsoleLogPageView : NIOverviewPageView { @private UIScrollView* _logScrollView; UILabel* _logLabel; } @end /** * A page that allows you to modify NIMaxLogLevel. * * @image html overview-maxloglevel1.png "The max log level page." * * @ingroup Overview-Pages */ @interface NIOverviewMaxLogLevelPageView : NIOverviewPageView { @private UISlider* _logLevelSlider; UILabel* _errorLogLevelLabel; UILabel* _warningLogLevelLabel; UILabel* _infoLogLevelLabel; } @end /** * A page that shows information regarding an in-memory cache. * * @ingroup Overview-Pages */ @interface NIOverviewMemoryCachePageView : NIOverviewGraphPageView /** * Returns an autoreleased instance of this page with the given cache. */ + (id)pageWithCache:(NIMemoryCache *)cache; @property (nonatomic, strong) NIMemoryCache* cache; @end /** * A page that adds run-time inspection features. * * @ingroup Overview-Pages */ @interface NIInspectionOverviewPageView : NIOverviewPageView @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewPageView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewPageView.h" #if defined(DEBUG) || defined(NI_DEBUG) #import "NIOverview.h" #import "NIOverviewView.h" #import "NIDeviceInfo.h" #import "NIOverviewGraphView.h" #import "NIOverviewLogger.h" #import "NimbusCore.h" #import <QuartzCore/QuartzCore.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif static UIEdgeInsets kPagePadding; static const CGFloat kGraphRightMargin = 5; @interface NSObject () - (id)initWithMemoryCache:(NIMemoryCache *)memoryCache; @end @implementation NIOverviewPageView + (void)initialize { kPagePadding = UIEdgeInsetsMake(5, 5, 10, 5); } + (NIOverviewPageView *)page { return [[[self class] alloc] initWithFrame:CGRectZero]; } - (UILabel *)label { UILabel* label = [[UILabel alloc] init]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont boldSystemFontOfSize:12]; label.textColor = [UIColor whiteColor]; if (!NIIsTintColorGloballySupported()) { label.shadowColor = [UIColor colorWithWhite:0 alpha:0.5f]; label.shadowOffset = CGSizeMake(0, 1); } return label; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.clipsToBounds = YES; _titleLabel = [[UILabel alloc] init]; _titleLabel.backgroundColor = [UIColor clearColor]; _titleLabel.font = [UIFont boldSystemFontOfSize:11]; _titleLabel.textColor = [UIColor colorWithWhite:1 alpha:0.8f]; [self addSubview:_titleLabel]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; [_titleLabel sizeToFit]; CGRect frame = _titleLabel.frame; frame.origin.x = floorf((self.bounds.size.width - frame.size.width) / 2); frame.origin.y = self.bounds.size.height - frame.size.height; _titleLabel.frame = frame; } - (void)setPageTitle:(NSString *)pageTitle { if (_pageTitle != pageTitle) { _pageTitle = [pageTitle copy]; _titleLabel.text = _pageTitle; [self setNeedsLayout]; } } - (void)update { // No-op. } @end @implementation NIOverviewGraphPageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Memory", @"Overview Page Title: Memory"); _label1 = [self label]; [self addSubview:_label1]; _label2 = [self label]; [self addSubview:_label2]; _graphView = [[NIOverviewGraphView alloc] init]; _graphView.dataSource = self; [self addSubview:_graphView]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; CGFloat contentWidth = self.frame.size.width - kPagePadding.left - kPagePadding.right; CGFloat contentHeight = self.frame.size.height - kPagePadding.top - kPagePadding.bottom; [_label1 sizeToFit]; [_label2 sizeToFit]; CGFloat maxLabelWidth = MAX(_label1.frame.size.width, _label2.frame.size.width); CGFloat remainingContentWidth = contentWidth - maxLabelWidth - kGraphRightMargin; CGRect frame = _label1.frame; frame.origin.x = kPagePadding.left + remainingContentWidth + kGraphRightMargin; frame.origin.y = kPagePadding.top; _label1.frame = frame; frame = _label2.frame; frame.origin.x = kPagePadding.left + remainingContentWidth + kGraphRightMargin; frame.origin.y = CGRectGetMaxY(_label1.frame); _label2.frame = frame; frame = self.titleLabel.frame; frame.origin.x = kPagePadding.left + remainingContentWidth + kGraphRightMargin; frame.origin.y = CGRectGetMaxY(_label2.frame); self.titleLabel.frame = frame; _graphView.frame = CGRectMake(kPagePadding.left, kPagePadding.top, remainingContentWidth, contentHeight); } - (void)update { [_graphView setNeedsDisplay]; } #pragma mark - NIOverviewGraphViewDataSource - (CGFloat)graphViewXRange:(NIOverviewGraphView *)graphView { NSMutableOrderedSet* deviceLogs = [[NIOverview logger] deviceLogs]; NIOverviewLogEntry* firstEntry = [deviceLogs firstObject]; NIOverviewLogEntry* lastEntry = [deviceLogs lastObject]; NSTimeInterval interval = [lastEntry.timestamp timeIntervalSinceDate:firstEntry.timestamp]; return (CGFloat)interval; } - (CGFloat)graphViewYRange:(NIOverviewGraphView *)graphView { return 0; } - (void)resetPointIterator { } - (BOOL)nextPointInGraphView: (NIOverviewGraphView *)graphView point: (CGPoint *)point { return NO; } - (NSDate *)initialTimestamp { return nil; } - (void)resetEventIterator { _eventEnumerator = [[[NIOverview logger] eventLogs] objectEnumerator]; } - (BOOL)nextEventInGraphView: (NIOverviewGraphView *)graphView xValue: (CGFloat *)xValue color: (UIColor **)color { static NSArray* sEventColors = nil; if (nil == sEventColors) { sEventColors = [NSArray arrayWithObjects: [UIColor redColor], // NIOverviewEventDidReceiveMemoryWarning nil]; } NIOverviewEventLogEntry* entry = [_eventEnumerator nextObject]; if (nil != entry) { NSTimeInterval interval = [entry.timestamp timeIntervalSinceDate:[self initialTimestamp]]; *xValue = (CGFloat)interval; *color = [sEventColors objectAtIndex:entry.type]; } return nil != entry; } @end @implementation NIOverviewMemoryPageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Memory", @"Overview Page Title: Memory"); self.graphView.dataSource = self; UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)]; // We still want to be able to drag the pages. tap.cancelsTouchesInView = NO; [self addGestureRecognizer:tap]; } return self; } - (void)update { [super update]; [NIDeviceInfo beginCachedDeviceInfo]; self.label1.text = [NSString stringWithFormat:@"%@ free", NIStringFromBytes([NIDeviceInfo bytesOfFreeMemory])]; self.label2.text = [NSString stringWithFormat:@"%@ total", NIStringFromBytes([NIDeviceInfo bytesOfTotalMemory])]; [NIDeviceInfo endCachedDeviceInfo]; [self setNeedsLayout]; } - (void)didTap:(UIGestureRecognizer *)gesture { // Simulate low memory warning while tapping on NIOverviewMemoryPageView [NIDeviceInfo simulateLowMemoryWarning]; } #pragma mark - NIOverviewGraphViewDataSource - (CGFloat)graphViewYRange:(NIOverviewGraphView *)graphView { NSMutableOrderedSet* deviceLogs = [[NIOverview logger] deviceLogs]; if ([deviceLogs count] == 0) { return 0; } unsigned long long minY = (unsigned long long)-1; unsigned long long maxY = 0; for (NIOverviewDeviceLogEntry* entry in deviceLogs) { minY = MIN(entry.bytesOfFreeMemory, minY); maxY = MAX(entry.bytesOfFreeMemory, maxY); } unsigned long long range = maxY - minY; _minMemory = minY; return (CGFloat)((double)range / 1024.0 / 1024.0); } - (void)resetPointIterator { _enumerator = [[[NIOverview logger] deviceLogs] objectEnumerator]; } - (NSDate *)initialTimestamp { NSMutableOrderedSet* deviceLogs = [[NIOverview logger] deviceLogs]; NIOverviewLogEntry* firstEntry = [deviceLogs firstObject]; return firstEntry.timestamp; } - (BOOL)nextPointInGraphView: (NIOverviewGraphView *)graphView point: (CGPoint *)point { NIOverviewDeviceLogEntry* entry = [_enumerator nextObject]; if (nil != entry) { NSTimeInterval interval = [entry.timestamp timeIntervalSinceDate:[self initialTimestamp]]; *point = CGPointMake((CGFloat)interval, (CGFloat)(((double)(entry.bytesOfFreeMemory - _minMemory)) / 1024.0 / 1024.0)); } return nil != entry; } @end @implementation NIOverviewDiskPageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Storage", @"Overview Page Title: Storage"); self.graphView.dataSource = self; } return self; } - (void)update { [super update]; [NIDeviceInfo beginCachedDeviceInfo]; self.label1.text = [NSString stringWithFormat:@"%@ free", NIStringFromBytes([NIDeviceInfo bytesOfFreeDiskSpace])]; self.label2.text = [NSString stringWithFormat:@"%@ total", NIStringFromBytes([NIDeviceInfo bytesOfTotalDiskSpace])]; [NIDeviceInfo endCachedDeviceInfo]; [self setNeedsLayout]; } #pragma mark - NIOverviewGraphViewDataSource - (CGFloat)graphViewYRange:(NIOverviewGraphView *)graphView { NSMutableOrderedSet* deviceLogs = [[NIOverview logger] deviceLogs]; if ([deviceLogs count] == 0) { return 0; } unsigned long long minY = (unsigned long long)-1; unsigned long long maxY = 0; for (NIOverviewDeviceLogEntry* entry in deviceLogs) { minY = MIN(entry.bytesOfFreeDiskSpace, minY); maxY = MAX(entry.bytesOfFreeDiskSpace, maxY); } unsigned long long range = maxY - minY; _minDiskUse = minY; return (CGFloat)((double)range / 1024.0 / 1024.0); } - (void)resetPointIterator { _enumerator = [[[NIOverview logger] deviceLogs] objectEnumerator]; } - (NSDate *)initialTimestamp { NSMutableOrderedSet* deviceLogs = [[NIOverview logger] deviceLogs]; NIOverviewLogEntry* firstEntry = [deviceLogs firstObject]; return firstEntry.timestamp; } - (BOOL)nextPointInGraphView: (NIOverviewGraphView *)graphView point: (CGPoint *)point { NIOverviewDeviceLogEntry* entry = [_enumerator nextObject]; if (nil != entry) { NSTimeInterval interval = [entry.timestamp timeIntervalSinceDate:[self initialTimestamp]]; double difference = ((double)entry.bytesOfFreeDiskSpace / 1024.0 / 1024.0 - (double)_minDiskUse / 1024.0 / 1024.0); *point = CGPointMake((CGFloat)interval, (CGFloat)difference); } return nil != entry; } @end @implementation NIOverviewConsoleLogPageView - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (UILabel *)label { UILabel* label = [[UILabel alloc] init]; label.font = [UIFont boldSystemFontOfSize:11]; label.textColor = [UIColor whiteColor]; if (!NIIsTintColorGloballySupported()) { label.shadowColor = [UIColor colorWithWhite:0 alpha:0.5f]; label.shadowOffset = CGSizeMake(0, 1); } label.backgroundColor = [UIColor clearColor]; label.lineBreakMode = NSLineBreakByWordWrapping; label.numberOfLines = 0; return label; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Logs", @"Overview Page Title: Logs"); self.titleLabel.textColor = [UIColor colorWithWhite:1 alpha:0.5f]; _logScrollView = [[UIScrollView alloc] initWithFrame:self.bounds]; _logScrollView.showsHorizontalScrollIndicator = NO; _logScrollView.alwaysBounceVertical = YES; _logScrollView.contentInset = kPagePadding; _logScrollView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2f]; [self addSubview:_logScrollView]; _logLabel = [self label]; [_logScrollView addSubview:_logLabel]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(didAddLog:) name: NIOverviewLoggerDidAddConsoleLog object: nil]; } return self; } - (void)contentSizeChanged { BOOL isBottomNearby = NO; if (_logScrollView.contentOffset.y + _logScrollView.bounds.size.height >= _logScrollView.contentSize.height - _logScrollView.bounds.size.height) { isBottomNearby = YES; } _logScrollView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height); CGSize labelSize = [_logLabel.text sizeWithFont: _logLabel.font constrainedToSize: CGSizeMake(_logScrollView.bounds.size.width, CGFLOAT_MAX) lineBreakMode: _logLabel.lineBreakMode]; _logLabel.frame = CGRectMake(0, 0, labelSize.width, labelSize.height); _logScrollView.contentSize = CGSizeMake(_logScrollView.bounds.size.width - kPagePadding.left - kPagePadding.right, _logLabel.frame.size.height); if (isBottomNearby) { _logScrollView.contentOffset = CGPointMake(-kPagePadding.left, MAX(_logScrollView.contentSize.height - _logScrollView.bounds.size.height + kPagePadding.top, -kPagePadding.top)); [_logScrollView flashScrollIndicators]; } } - (void)setFrame:(CGRect)frame { [super setFrame:frame]; [self contentSizeChanged]; } - (void)layoutSubviews { [super layoutSubviews]; CGRect labelFrame = self.titleLabel.frame; labelFrame.origin.x = (self.bounds.size.width - kPagePadding.right - self.titleLabel.frame.size.width); labelFrame.origin.y = (self.bounds.size.height - kPagePadding.bottom - self.titleLabel.frame.size.height); self.titleLabel.frame = labelFrame; } - (void)didAddLog:(NSNotification *)notification { NIOverviewConsoleLogEntry* entry = [[notification userInfo] objectForKey:@"entry"]; static NSDateFormatter* formatter = nil; if (nil == formatter) { formatter = [[NSDateFormatter alloc] init]; [formatter setTimeStyle:NSDateFormatterShortStyle]; [formatter setDateStyle:NSDateFormatterNoStyle]; } NSString* formattedLog = [NSString stringWithFormat:@"%@: %@", [formatter stringFromDate:entry.timestamp], entry.log]; if (nil != _logLabel.text) { _logLabel.text = [_logLabel.text stringByAppendingFormat:@"\n%@", formattedLog]; } else { _logLabel.text = formattedLog; } [self contentSizeChanged]; } @end @implementation NIOverviewMaxLogLevelPageView - (UILabel *)label { UILabel* label = [[UILabel alloc] init]; label.font = [UIFont boldSystemFontOfSize:11]; label.textColor = [UIColor whiteColor]; if (!NIIsTintColorGloballySupported()) { label.shadowColor = [UIColor colorWithWhite:0 alpha:0.5f]; label.shadowOffset = CGSizeMake(0, 1); } label.backgroundColor = [UIColor clearColor]; label.lineBreakMode = NSLineBreakByWordWrapping; label.numberOfLines = 0; return label; } - (void)updateLabels { _warningLogLevelLabel.textColor = [_warningLogLevelLabel.textColor colorWithAlphaComponent: (NIMaxLogLevel >= NILOGLEVEL_WARNING) ? 1 : 0.6f]; _infoLogLevelLabel.textColor = [_infoLogLevelLabel.textColor colorWithAlphaComponent: (NIMaxLogLevel >= NILOGLEVEL_INFO) ? 1 : 0.6f]; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Max Log Level", @"Overview Page Title: Max Log Level"); self.titleLabel.textColor = [UIColor colorWithWhite:1 alpha:0.5f]; _logLevelSlider = [[UISlider alloc] init]; _logLevelSlider.minimumValue = 1; _logLevelSlider.maximumValue = 5; [_logLevelSlider addTarget: self action: @selector(didChangeSliderValue:) forControlEvents: UIControlEventValueChanged]; [self addSubview:_logLevelSlider]; _logLevelSlider.value = NIMaxLogLevel; _errorLogLevelLabel = [self label]; _warningLogLevelLabel = [self label]; _infoLogLevelLabel = [self label]; _errorLogLevelLabel.text = NSLocalizedString(@"Error", @"Maximum log level: error"); _warningLogLevelLabel.text = NSLocalizedString(@"Warning", @"Maximum log level: warning"); _infoLogLevelLabel.text = NSLocalizedString(@"Info", @"Maximum log level: info"); [self addSubview:_errorLogLevelLabel]; [self addSubview:_warningLogLevelLabel]; [self addSubview:_infoLogLevelLabel]; [self updateLabels]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; CGFloat contentSize = self.bounds.size.width - kPagePadding.left - kPagePadding.right; _logLevelSlider.frame = CGRectMake(kPagePadding.left, kPagePadding.top, contentSize, 20); CGFloat sliderBottom = CGRectGetMaxY(_logLevelSlider.frame); [_errorLogLevelLabel sizeToFit]; _errorLogLevelLabel.frame = CGRectMake(kPagePadding.left, sliderBottom, _errorLogLevelLabel.frame.size.width, _errorLogLevelLabel.frame.size.height); [_warningLogLevelLabel sizeToFit]; _warningLogLevelLabel.frame = CGRectMake(floorf((self.bounds.size.width - _warningLogLevelLabel.frame.size.width) / 2), sliderBottom, _warningLogLevelLabel.frame.size.width, _warningLogLevelLabel.frame.size.height); [_infoLogLevelLabel sizeToFit]; _infoLogLevelLabel.frame = CGRectMake(kPagePadding.left + contentSize - _infoLogLevelLabel.frame.size.width, sliderBottom, _infoLogLevelLabel.frame.size.width, _infoLogLevelLabel.frame.size.height); } - (void)didChangeSliderValue:(UISlider *)slider { slider.value = roundf(slider.value); NIMaxLogLevel = lround(slider.value); [self updateLabels]; } @end @interface NIOverviewMemoryCacheEntry : NSObject @property (nonatomic, retain) NSDate* timestamp; @property (nonatomic, assign) NSUInteger numberOfObjects; @end @implementation NIOverviewMemoryCacheEntry @end @interface NIOverviewImageMemoryCacheEntry : NIOverviewMemoryCacheEntry @property (nonatomic, assign) NSUInteger numberOfPixels; @property (nonatomic, assign) NSUInteger maxNumberOfPixels; @property (nonatomic, assign) NSUInteger maxNumberOfPixelsUnderStress; @end @implementation NIOverviewImageMemoryCacheEntry @end @interface NIOverviewMemoryCachePageView() @property (nonatomic) unsigned long long minValue; @property (nonatomic, strong) NSEnumerator* enumerator; @property (nonatomic, strong) NSMutableOrderedSet* history; @end @implementation NIOverviewMemoryCachePageView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = NSLocalizedString(@"Memory Cache", @"Overview Page Title: Memory Cache"); self.cache = [Nimbus imageMemoryCache]; self.history = [[NSMutableOrderedSet alloc] init]; self.graphView.dataSource = self; UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)]; // We still want to be able to drag the pages. tap.cancelsTouchesInView = NO; [self addGestureRecognizer:tap]; } return self; } + (id)pageWithCache:(NIMemoryCache *)cache { NIOverviewMemoryCachePageView* pageView = [[[self class] alloc] initWithFrame:CGRectZero]; pageView.cache = cache; return pageView; } - (void)update { [super update]; NIOverviewMemoryCacheEntry* entry = nil; // Update the labels. if ([self.cache isKindOfClass:[NIImageMemoryCache class]]) { NIImageMemoryCache* imageCache = (NIImageMemoryCache *)self.cache; self.label1.text = [NSString stringWithFormat:@"%@ total", NIStringFromBytes(imageCache.numberOfPixels)]; self.label2.text = [NSString stringWithFormat:@"%@|%@", NIStringFromBytes(imageCache.maxNumberOfPixelsUnderStress), NIStringFromBytes(imageCache.maxNumberOfPixels)]; NIOverviewImageMemoryCacheEntry* imageEntry = [[NIOverviewImageMemoryCacheEntry alloc] init]; imageEntry.numberOfPixels = imageCache.numberOfPixels; imageEntry.maxNumberOfPixels = imageCache.maxNumberOfPixels; imageEntry.maxNumberOfPixelsUnderStress = imageCache.maxNumberOfPixelsUnderStress; entry = imageEntry; } else { self.label1.text = [NSString stringWithFormat:@"%d objects", self.cache.count]; self.label2.text = nil; entry = [[NIOverviewMemoryCacheEntry alloc] init]; } entry.timestamp = [NSDate date]; entry.numberOfObjects = self.cache.count; [self.history addObject:entry]; NSDate* cutoffDate = [NSDate dateWithTimeIntervalSinceNow:-[NIOverview logger].oldestLogAge]; while ([[(NIOverviewMemoryCacheEntry *)self.history.firstObject timestamp] compare:cutoffDate] == NSOrderedAscending) { [self.history removeObjectAtIndex:0]; } [self setNeedsLayout]; } - (void)didTap:(UIGestureRecognizer *)gesture { UIViewController* rootController = [UIApplication sharedApplication].keyWindow.rootViewController; if ([rootController respondsToSelector:@selector(pushViewController:animated:)]) { // We want a weak dependency on the overview memory cache controller so that we don't force // a dependency on the models feature. Class class = NSClassFromString(@"NIOverviewMemoryCacheController"); if (nil != class) { id instance = [class alloc]; SEL initSelector = @selector(initWithMemoryCache:); NIDASSERT([instance respondsToSelector:initSelector]); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" UIViewController* controller = [instance performSelector:initSelector withObject:self.cache]; #pragma clang diagnostic pop controller.title = @"Memory Cache"; [(id)rootController pushViewController:controller animated:YES]; } } } #pragma mark - NIOverviewGraphViewDataSource - (CGFloat)graphViewYRange:(NIOverviewGraphView *)graphView { if (0 == self.history.count) { return 0; } unsigned long long minY = (unsigned long long)-1; unsigned long long maxY = 0; if ([self.cache isKindOfClass:[NIImageMemoryCache class]]) { // For image caches we want to show the number of pixels over time. for (NIOverviewImageMemoryCacheEntry* entry in self.history) { minY = MIN(entry.numberOfPixels, minY); maxY = MAX(entry.numberOfPixels, maxY); } unsigned long long range = maxY - minY; self.minValue = minY; return (CGFloat)((double)range / 1024.0 / 1024.0); } else { // For regular memory caches we'll just show the count of objects. for (NIOverviewMemoryCacheEntry* entry in self.history) { minY = MIN(entry.numberOfObjects, minY); maxY = MAX(entry.numberOfObjects, maxY); } unsigned long long range = maxY - minY; self.minValue = minY; return (CGFloat)range; } } - (void)resetPointIterator { _enumerator = [self.history objectEnumerator]; } - (NSDate *)initialTimestamp { NIOverviewMemoryCacheEntry* entry = self.history.firstObject; return entry.timestamp; } - (BOOL)nextPointInGraphView: (NIOverviewGraphView *)graphView point: (CGPoint *)point { NIOverviewMemoryCacheEntry* entry = [_enumerator nextObject]; if (nil != entry) { NSTimeInterval interval = [entry.timestamp timeIntervalSinceDate:[self initialTimestamp]]; if ([self.cache isKindOfClass:[NIImageMemoryCache class]]) { NIOverviewImageMemoryCacheEntry* imageEntry = (NIOverviewImageMemoryCacheEntry *)entry; *point = CGPointMake((CGFloat)interval, (CGFloat)(((double)(imageEntry.numberOfPixels - self.minValue)) / 1024.0 / 1024.0)); } else { *point = CGPointMake((CGFloat)interval, (CGFloat)(entry.numberOfObjects - self.minValue)); } } return nil != entry; } @end typedef BOOL (^NIViewRecursionBlock)(UIView *view); static const CGFloat kButtonSize = 44; static const CGFloat kButtonMargin = 5; static const CGFloat kMinimumFontSize = 12; static const CGFloat kPadding = 10; static const CGFloat kAvoidedTopHeight = 80; static const NSTimeInterval kAutoresizingAnimationDuration = 2; @class NIViewInspectionView; static NIViewInspectionView *visibleInspectionView = nil; @interface NIViewInspectionView : UIView @end @implementation NIViewInspectionView { UIView *touchedView_; UIView *interactingView_; // For displaying the autoresizing mask visually. UIView *containerView_; UIView *autoresizingView_; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // We want our touches to hit the real application views beneath this view. self.userInteractionEnabled = NO; self.opaque = NO; } return self; } - (void)drawRect:(CGRect)rect { CGRect bounds = self.bounds; CGContextRef cx = UIGraphicsGetCurrentContext(); CGContextClearRect(cx, bounds); if (touchedView_) { [[UIColor colorWithWhite:0 alpha:0.8f] set]; UIRectFill(bounds); CGRect frame = [touchedView_ convertRect:touchedView_.bounds toView:self]; if (!CGRectEqualToRect(frame, bounds)) { CGContextClearRect(cx, frame); } [[UIColor colorWithWhite:0 alpha:0.1f] set]; UIRectFrame(frame); [[UIColor whiteColor] set]; CGPoint offset = CGPointMake(kPadding, NIStatusBarHeight() + kPadding); if (CGRectGetMaxY(frame) - kAvoidedTopHeight < offset.y) { offset.y += kAvoidedTopHeight; } NSString *responder = [NSString stringWithFormat:@"%@ (%p)", NSStringFromClass([interactingView_ class]), interactingView_]; offset.y += [self drawTitle:@"Responder: " value:responder atPoint:offset]; NSString *touched = [NSString stringWithFormat:@"%@ (%p)", NSStringFromClass([touchedView_ class]), touchedView_]; offset.y += [self drawTitle:@"Touched: " value:touched atPoint:offset]; offset.y += [self drawTitle:@"Frame: " value:NSStringFromCGRect(touchedView_.frame) atPoint:offset]; UILabel *label = nil; if ([touchedView_ isKindOfClass:[UILabel class]]) { label = (UILabel *)touchedView_; } else if ([touchedView_ isKindOfClass:[UIButton class]]) { UIButton *button = (UIButton *)touchedView_; label = (UILabel *)button.titleLabel; // Display button title frame as well. offset.y += [self drawTitle:@"Title frame: " value:NSStringFromCGRect(label.frame) atPoint:offset]; } if (label) { const CGFloat *components = CGColorGetComponents(label.textColor.CGColor); offset.y += [self drawTitle:@"Font: " value:[NSString stringWithFormat:@"%0.1fpx, " "color: (%x,%x,%x)", label.font.pointSize, (int)(components[0]*255), (int)(components[1]*255), (int)(components[2]*255)] atPoint:offset]; } } else { [[UIColor colorWithWhite:1 alpha:0.5f] set]; UIRectFill(bounds); [[UIColor colorWithWhite:0.5 alpha:0.5f] set]; UIRectFrame(NIRectShift(CGRectInset(bounds, kPadding, kPadding), 0, NIStatusBarHeight())); } } - (CGFloat)drawTitle:(NSString *)title value:(NSString *)value atPoint:(CGPoint)point { UIFont *infoFont = [UIFont systemFontOfSize:[UIFont systemFontSize]]; CGSize size = [title drawAtPoint:point withFont:infoFont]; point = CGPointMake(point.x + size.width, point.y); CGRect bounds = self.bounds; [value drawAtPoint:point forWidth:bounds.size.width - point.x - kPadding withFont:infoFont minFontSize:kMinimumFontSize actualFontSize:nil lineBreakMode:NSLineBreakByTruncatingMiddle baselineAdjustment:UIBaselineAdjustmentAlignBaselines]; return size.height; } - (void)setTouchedView:(UIView *)view interactingView:(UIView *)interactingView { interactingView_ = interactingView; if (touchedView_ != view) { touchedView_ = view; [containerView_ removeFromSuperview]; containerView_ = [[UIView alloc] init]; containerView_.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7f]; autoresizingView_ = [[UIView alloc] init]; autoresizingView_.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5f]; autoresizingView_.layer.borderColor = [UIColor colorWithWhite:0 alpha:0.2f].CGColor; autoresizingView_.layer.borderWidth = 1; autoresizingView_.autoresizingMask = view.autoresizingMask; [self addSubview:containerView_]; [containerView_ addSubview:autoresizingView_]; containerView_.frame = CGRectMake(kPadding, self.bounds.size.height - 80 - 30 - kPadding, 100, 80); autoresizingView_.frame = CGRectInset(containerView_.bounds, 20, 20); void (^animationBlock)(void) = ^{ containerView_.frame = NIRectExpand(containerView_.frame, 50, 30); }; [UIView animateWithDuration:kAutoresizingAnimationDuration delay:0 options:(UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:animationBlock completion:nil]; } [self setNeedsDisplay]; } @end @interface UIView (DebugUtilities) @property (nonatomic, assign) BOOL debugColorizeSubviews; - (void)recurseWithCallback:(NIViewRecursionBlock)callback; @end @implementation UIView (DebugUtilities) @dynamic debugColorizeSubviews; - (void)recurseWithCallback:(NIViewRecursionBlock)callback { if (callback(self)) { for (UIView *subview in self.subviews) { [subview recurseWithCallback:callback]; } } } @end @interface UIWindow (Interceptor) @end @implementation UIWindow (Interceptor) - (void)_azInterceptSendEvent:(UIEvent *)event { if (event.type == UIEventTypeTouches) { UITouch *touch = [[event allTouches] anyObject]; if ([touch.view isDescendantOfView:[NIOverview view]]) { [self _azInterceptSendEvent:event]; } else { UIView *interactingView = touch.view; CGPoint touchPoint = [touch locationInView:self]; __block UIView *touchedView = [self hitTest:[touch locationInView:self] withEvent:event]; [touchedView recurseWithCallback:^(UIView *view) { CGPoint viewPoint = [view convertPoint:touchPoint fromView:self]; if ([view pointInside:viewPoint withEvent:event]) { touchedView = view; if ([touchedView isKindOfClass:[UIButton class]] || [touchedView isKindOfClass:[UITextField class]]) { // Don't select any subviews of these classes. return NO; } } return YES; }]; [visibleInspectionView setTouchedView:touchedView interactingView:interactingView]; } } else { [self _azInterceptSendEvent:event]; } } @end @implementation NIInspectionOverviewPageView { NSArray *buttons_; NIViewInspectionView *inspectionView_; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.pageTitle = @"Inspection"; UIButton *colorizeButton = [UIButton buttonWithType:UIButtonTypeCustom]; [colorizeButton setBackgroundImage:[self backgroundForColorizeButton] forState:UIControlStateNormal]; colorizeButton.frame = CGRectMake(0, 0, kButtonSize, kButtonSize); [self addSubview:colorizeButton]; [colorizeButton addTarget:self action:@selector(didTapColorizeButton:) forControlEvents:UIControlEventTouchUpInside]; UIButton *pinpointButton = [UIButton buttonWithType:UIButtonTypeCustom]; [pinpointButton setBackgroundImage:[self backgroundForPinpointButton] forState:UIControlStateNormal]; pinpointButton.frame = CGRectMake(0, 0, kButtonSize, kButtonSize); [self addSubview:pinpointButton]; [pinpointButton addTarget:self action:@selector(didTapPinpointButton:) forControlEvents:UIControlEventTouchUpInside]; buttons_ = [NSArray arrayWithObjects:colorizeButton, pinpointButton, nil]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; CGFloat leftEdge = kButtonMargin; for (UIButton *button in buttons_) { CGRect frame = button.frame; frame.origin = CGPointMake(leftEdge, kButtonMargin); button.frame = frame; leftEdge = CGRectGetMaxX(button.frame) + kButtonMargin; } } #pragma mark - User Actions - (void)didTapColorizeButton:(UIButton *)button { [[self rootView] recurseWithCallback:^(UIView *view) { if ([view respondsToSelector:@selector(setDebugColorizeSubviews:)]) { [(id)view setDebugColorizeSubviews:YES]; [view setNeedsLayout]; } return YES; }]; } - (void)didTapPinpointButton:(UIButton *)button { NISwapInstanceMethods([UIWindow class], @selector(sendEvent:), @selector(_azInterceptSendEvent:)); if (inspectionView_ != nil) { [inspectionView_ removeFromSuperview]; inspectionView_ = nil; visibleInspectionView = nil; return; } UIView *rootView = [self rootView]; [rootView endEditing:YES]; inspectionView_ = [[NIViewInspectionView alloc] initWithFrame:rootView.bounds]; inspectionView_.autoresizingMask = UIViewAutoresizingFlexibleDimensions; [rootView addSubview:inspectionView_]; visibleInspectionView = inspectionView_; } #pragma mark - Utilities - (UIView *)rootView { return [UIApplication sharedApplication].keyWindow.rootViewController.view; } #pragma mark - Button Images - (UIColor *)randomColor { return RGBCOLOR(arc4random_uniform(128) + 128, arc4random_uniform(128) + 128, arc4random_uniform(128) + 128); } - (UIImage *)backgroundForColorizeButton { CGRect imageRect = CGRectMake(0, 0, kButtonSize, kButtonSize); UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0); CGContextRef cx = UIGraphicsGetCurrentContext(); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); NSArray *gradientColors = [NSMutableArray arrayWithObjects: (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, (id)[self randomColor].CGColor, nil]; CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, nil); CGColorSpaceRelease(colorSpace); colorSpace = nil; CGContextDrawRadialGradient(cx, gradient, CGPointMake(0, 0), 0, CGPointMake(kButtonSize, kButtonSize), kButtonSize, 0); CGGradientRelease(gradient); gradient = nil; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } - (UIImage *)backgroundForPinpointButton { CGRect imageRect = CGRectMake(0, 0, kButtonSize, kButtonSize); UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, 0); CGContextRef cx = UIGraphicsGetCurrentContext(); [[UIColor whiteColor] set]; CGContextStrokeEllipseInRect(cx, CGRectInset(imageRect, 10, 10)); CGFloat midX = CGRectGetMidX(imageRect); CGFloat midY = CGRectGetMidY(imageRect); CGContextBeginPath(cx); CGContextMoveToPoint(cx, midX, midY - kButtonSize / 2); CGContextAddLineToPoint(cx, midX, midY + kButtonSize / 2); CGContextMoveToPoint(cx, midX - kButtonSize / 2, midY); CGContextAddLineToPoint(cx, midX + kButtonSize / 2, midY); CGContextStrokePath(cx); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewSwizzling.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> /** * Returns the true status bar height when the Overview is active. * * @ingroup Overview-Tools * * The Overview swizzles the methods used by NIStatusBarHeight. */ CGFloat NIOverviewStatusBarHeight(); /** * Swizzles all the necessary methods to get the Overview working. * * @ingroup Overview-Tools */ void NIOverviewSwizzleMethods();
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewSwizzling.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewSwizzling.h" #import "NimbusCore.h" #import "NIOverview.h" #import "NIOverviewView.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif #if defined(DEBUG) || defined(NI_DEBUG) @interface UIApplication (Private) - (CGRect)_statusBarFrame; - (CGFloat)statusBarHeightForOrientation:(UIInterfaceOrientation)orientation; @end @interface UIViewController (Private) - (CGFloat)_statusBarHeightForCurrentInterfaceOrientation; - (CGFloat)_statusBarHeightAdjustmentForCurrentOrientation; @end CGFloat NIOverviewStatusBarHeight(void); void NIOverviewSwizzleMethods(void); CGFloat NIOverviewStatusBarHeight(void) { CGRect statusBarFrame = [[UIApplication sharedApplication] _statusBarFrame]; CGFloat statusBarHeight = MIN(statusBarFrame.size.width, statusBarFrame.size.height); return statusBarHeight; } @implementation UIViewController (NIDebugging) /** * Swizzled implementation of private API - (float)_statusBarHeightAdjustmentForCurrentOrientation * * This method is used by view controllers to adjust the size of their views on iOS 7 devices. */ - (float)__statusBarHeightAdjustmentForCurrentOrientation { return NIOverviewStatusBarHeight() + [NIOverview height]; } /** * Swizzled implementation of private API - (float)_statusBarHeightForCurrentInterfaceOrientation * * This method is used by view controllers to adjust the size of their views on pre-iOS 7 devices. */ - (float)__statusBarHeightForCurrentInterfaceOrientation { return NIOverviewStatusBarHeight() + [NIOverview height]; } @end @implementation UIApplication (NIDebugging) /** * Swizzled implementation of - (CGRect)statusBarFrame * * The real magic that causes view controllers to adjust their sizes happens in * __statusBarHeightForCurrentInterfaceOrientation. This method is swizzled purely * for application-level code that depends on statusBarFrame for calculations. */ - (CGRect)_statusBarFrame { return CGRectMake(0, 0, CGFLOAT_MAX, NIOverviewStatusBarHeight() + [NIOverview height]); } /** * Swizzled implementation of - (void)statusBarHeightForOrientation: * * This allows us to make the status bar larger for view controllers that aren't in * navigation controllers. */ - (float)_statusBarHeightForOrientation:(int)arg1 { return NIOverviewStatusBarHeight() + [NIOverview height]; } /** * Swizzled implementation of - (void)setStatusBarHidden:withAnimation: * * This allows us to hide the overview when the status bar is hidden. */ - (void)_setStatusBarHidden:(BOOL)hidden withAnimation:(UIStatusBarAnimation)animation { [self _setStatusBarHidden:hidden withAnimation:animation]; if (UIStatusBarAnimationNone == animation) { [NIOverview view].alpha = 1; [NIOverview view].hidden = hidden; } else if (UIStatusBarAnimationSlide == animation) { [NIOverview view].alpha = 1; CGRect frame = [NIOverview frame]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:NIStatusBarAnimationDuration()]; [UIView setAnimationCurve:NIStatusBarAnimationCurve()]; [NIOverview view].frame = frame; [UIView commitAnimations]; } else if (UIStatusBarAnimationFade == animation) { CGRect frame = [NIOverview frame]; [NIOverview view].frame = frame; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:NIStatusBarAnimationDuration()]; [UIView setAnimationCurve:NIStatusBarAnimationCurve()]; [NIOverview view].alpha = hidden ? 0 : 1; [UIView commitAnimations]; } } /** * Swizzled implementation of - (void)setStatusBarStyle:animated: */ - (void)_setStatusBarStyle:(UIStatusBarStyle)statusBarStyle animated:(BOOL)animated { [self _setStatusBarStyle:statusBarStyle animated:animated]; if (animated) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; } // TODO (jverkoey July 23, 2011): Add a translucent property to the overview view. if (UIStatusBarStyleDefault == statusBarStyle || UIStatusBarStyleBlackOpaque == statusBarStyle) { [[NIOverview view] setTranslucent:NO]; } else if (UIStatusBarStyleBlackTranslucent == statusBarStyle) { [[NIOverview view] setTranslucent:YES]; } if (animated) { [UIView commitAnimations]; } } @end void NIOverviewSwizzleMethods(void) { NISwapInstanceMethods([UIViewController class], @selector(_statusBarHeightForCurrentInterfaceOrientation), @selector(__statusBarHeightForCurrentInterfaceOrientation)); NISwapInstanceMethods([UIViewController class], @selector(_statusBarHeightAdjustmentForCurrentOrientation), @selector(__statusBarHeightAdjustmentForCurrentOrientation)); NISwapInstanceMethods([UIApplication class], @selector(statusBarFrame), @selector(_statusBarFrame)); NISwapInstanceMethods([UIApplication class], @selector(statusBarHeightForOrientation:), @selector(_statusBarHeightForOrientation:)); NISwapInstanceMethods([UIApplication class], @selector(setStatusBarHidden:withAnimation:), @selector(_setStatusBarHidden:withAnimation:)); NISwapInstanceMethods([UIApplication class], @selector(setStatusBarStyle:animated:), @selector(_setStatusBarStyle:animated:)); } #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #if defined(DEBUG) || defined(NI_DEBUG) @class NIOverviewPageView; /** * The root scrolling page view of the Overview. * * @ingroup Overview */ @interface NIOverviewView : UIView /** * Whether the view has a translucent background or not. */ @property (nonatomic, assign) BOOL translucent; /** * Whether the view can be draggable vertically or not. */ @property (nonatomic, assign) BOOL enableDraggingVertically; /** * Prepends a new page to the Overview. */ - (void)prependPageView:(NIOverviewPageView *)page; /** * Adds a new page to the Overview. */ - (void)addPageView:(NIOverviewPageView *)page; /** * Removes a page from the Overview. */ - (void)removePageView:(NIOverviewPageView *)page; /** * Update all of the views. */ - (void)updatePages; - (void)flashScrollIndicators; @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NIOverviewView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIOverviewView.h" #if defined(DEBUG) || defined(NI_DEBUG) #import "NimbusCore.h" #import "NIOverviewLogger.h" #import "NIDeviceInfo.h" #import "NIOverviewPageView.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif static const NSUInteger kNumberOfFingersForPanGestureRecognizer = 1; @interface NIOverviewView() - (CGFloat)pageHorizontalMargin; - (CGRect)frameForPagingScrollView; @end @implementation NIOverviewView { UIImage* _backgroundImage; // State BOOL _translucent; NSMutableArray* _pageViews; // Views UIScrollView* _pagingScrollView; // Gesture recognizer CGRect _initialFrame; UIPanGestureRecognizer *_panGestureRecognizer; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { _pageViews = [[NSMutableArray alloc] init]; _backgroundImage = [UIImage imageWithContentsOfFile: NIPathForBundleResource(nil, @"NimbusOverviewer.bundle/gfx/blueprint.gif")]; self.backgroundColor = NIIsTintColorGloballySupported() ? self.tintColor : [UIColor colorWithPatternImage:_backgroundImage]; _pagingScrollView = [[UIScrollView alloc] initWithFrame:[self frameForPagingScrollView]]; _pagingScrollView.pagingEnabled = YES; _pagingScrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, self.pageHorizontalMargin, 0, self.pageHorizontalMargin); _pagingScrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); [self addSubview:_pagingScrollView]; self.autoresizingMask = UIViewAutoresizingFlexibleWidth; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePages) name:NIOverviewLoggerDidAddDeviceLog object:nil]; _panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPanMapWithGestureRecognizer:)]; _panGestureRecognizer.maximumNumberOfTouches = kNumberOfFingersForPanGestureRecognizer; _panGestureRecognizer.minimumNumberOfTouches = kNumberOfFingersForPanGestureRecognizer; [self addGestureRecognizer:_panGestureRecognizer]; } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self name:NIOverviewLoggerDidAddDeviceLog object:nil]; } #pragma mark - Page Layout - (CGFloat)pageHorizontalMargin { return 10; } - (CGRect)frameForPagingScrollView { CGRect frame = self.bounds; // We make the paging scroll view a little bit wider on the side edges so that there // there is space between the pages when flipping through them. frame.origin.x -= self.pageHorizontalMargin; frame.size.width += (2 * self.pageHorizontalMargin); return frame; } - (CGSize)contentSizeForPagingScrollView { CGRect bounds = _pagingScrollView.bounds; return CGSizeMake(bounds.size.width * [_pageViews count], bounds.size.height); } - (CGRect)frameForPageAtIndex:(NSInteger)pageIndex { // We have to use our paging scroll view's bounds, not frame, to calculate the page // placement. When the device is in landscape orientation, the frame will still be in // portrait because the pagingScrollView is the root view controller's view, so its // frame is in window coordinate space, which is never rotated. Its bounds, however, // will be in landscape because it has a rotation transform applied. CGRect bounds = _pagingScrollView.bounds; CGRect pageFrame = bounds; // We need to counter the extra spacing added to the paging scroll view in // frameForPagingScrollView: pageFrame.size.width -= self.pageHorizontalMargin * 2; pageFrame.origin.x = (bounds.size.width * pageIndex) + self.pageHorizontalMargin; return pageFrame; } - (void)layoutPages { _pagingScrollView.contentSize = [self contentSizeForPagingScrollView]; for (NSUInteger ix = 0; ix < [_pageViews count]; ++ix) { UIView* pageView = [_pageViews objectAtIndex:ix]; pageView.frame = [self frameForPageAtIndex:ix]; } } - (NSInteger)visiblePageIndex { CGFloat offset = _pagingScrollView.contentOffset.x; CGFloat pageWidth = _pagingScrollView.bounds.size.width; return (NSInteger)(offset / pageWidth); } - (void)setBounds:(CGRect)bounds { NSInteger visiblePageIndex = [self visiblePageIndex]; [super setBounds:bounds]; [self layoutPages]; CGFloat pageWidth = _pagingScrollView.bounds.size.width; CGFloat newOffset = (visiblePageIndex * pageWidth); _pagingScrollView.contentOffset = CGPointMake(newOffset, 0); } - (void)setFrame:(CGRect)frame { NSInteger visiblePageIndex = [self visiblePageIndex]; [super setFrame:frame]; [self layoutPages]; CGFloat pageWidth = _pagingScrollView.bounds.size.width; CGFloat newOffset = (visiblePageIndex * pageWidth); _pagingScrollView.contentOffset = CGPointMake(newOffset, 0); } #pragma mark - Public - (void)setTranslucent:(BOOL)translucent { if (_translucent != translucent) { _translucent = translucent; _pagingScrollView.indicatorStyle = (_translucent ? UIScrollViewIndicatorStyleWhite : UIScrollViewIndicatorStyleDefault); self.backgroundColor = (_translucent ? [UIColor colorWithWhite:0 alpha:0.5f] : ((NIIsTintColorGloballySupported() && self.tintColor) ? self.tintColor : [UIColor colorWithPatternImage:_backgroundImage])); } } - (void)prependPageView:(NIOverviewPageView *)page { [_pageViews insertObject:page atIndex:0]; [_pagingScrollView addSubview:page]; [self layoutPages]; } - (void)addPageView:(NIOverviewPageView *)page { [_pageViews addObject:page]; [_pagingScrollView addSubview:page]; [self layoutPages]; } - (void)removePageView:(NIOverviewPageView *)page { [_pageViews removeObject:page]; [page removeFromSuperview]; [self layoutPages]; } - (void)updatePages { for (NIOverviewPageView* pageView in _pageViews) { [pageView update]; } } - (void)flashScrollIndicators { [_pagingScrollView flashScrollIndicators]; } #pragma mark - Gesture Recognizer - (void)didPanMapWithGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer { if (!_enableDraggingVertically || _panGestureRecognizer != gestureRecognizer) { return; } if (gestureRecognizer.state == UIGestureRecognizerStateBegan) { _initialFrame = self.frame; } else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) { CGPoint translation = [gestureRecognizer translationInView:self.superview]; UIInterfaceOrientation orientation = NIInterfaceOrientation(); CGRect rect = self.frame; CGRect superRect = self.superview.frame; if (UIInterfaceOrientationIsPortrait(orientation)) { CGFloat y = _initialFrame.origin.y + translation.y; rect.origin.y = MIN(MAX(y, 0), superRect.size.height - _initialFrame.size.height); } else if (UIInterfaceOrientationIsLandscape(orientation)) { CGFloat x = _initialFrame.origin.x + translation.x; rect.origin.x = MIN(MAX(x, 0), superRect.size.width - _initialFrame.size.width); } self.frame = rect; } } @end #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/overview/src/NimbusOverview.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> /** * @defgroup NimbusOverview Nimbus Overview * @{ * * <div id="github" feature="overview"></div> * * The Overview is a debugging tool for quickly understanding the current state of your * application. When added to an application, it will insert a paged * scroll view beneath the status bar that contains any number of pages of information. * These pages can show anything from graphs of current memory usage to console logs to * configuration settings. * * @image html overview1.png "The Overview added to the network photo album app." * * * <h2>Built-in Overview Pages</h2> * * The Overview comes with a few basic pages for viewing the device state and console logs. * * * <h3>NIOverviewMemoryPageView</h3> * * @image html overview-memory1.png "The memory page." * * This page shows a graph of the relative available memory on the device. * * * <h3>NIOverviewDiskPageView</h3> * * @image html overview-disk1.png "The disk page." * * This page shows a graph of the relative available disk space on the device. * * * <h3>NIOverviewConsoleLogPageView</h3> * * @image html overview-log1.png "The log page." * * This page shows all messages sent to NSLog since the Overview was initialized. * * * <h3>NIOverviewMaxLogLevelPageView</h3> * * @image html overview-maxloglevel1.png "The max log level page." * * This page allows you to modify NIMaxLogLevel while the app is running. * * * <h2>How to Use the Overview</h2> * * To begin using the Overview you need to add two lines of code to your app and define * DEBUG in your applicaton's preprocessor macros Debug target settings. * * @code - (BOOL) application:(UIApplication *)application * didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { * // Line #1 - Swizzles the necessary methods for making the Overview appear as part of the * // the status bar. * [NIOverview applicationDidFinishLaunching]; * * // After you create the UIWindow for your application and add the root view controller, * // i.e.: * [self.window addSubview:_rootViewController.view]; * * // then you add the Overview view to the window. * [NIOverview addOverviewToWindow:self.window]; * @endcode * * * <h2>Events</h2> * * Certain events are useful in providing context while debugging an application. When a * memory warning is received it can be helpful to see how much memory was released. for example. * * The Overview visually presents events on Overview graphs as vertical lines. Memory warnings * are red. * * In the screenshot below, you can see when a memory warning occurred and the resulting * increase in available memory. * * @image html overview-memorywarning1.png "A memory warning received on the iPad is shown with a vertical red line." * * <h2>How the Overview is Displayed</h2> * * The Overview is displayed by tricking the application into thinking that the status bar is * 60 pixels larger than it actually is. If your app respects the status bar frame correctly * then the Overview will always be visible above the chrome of your application, directly * underneath the status bar. If the status bar is hidden, the Overview will also be hidden. * * * <h2>Creating a Custom Page</h2> * * You can build your own page by subclassing NIOverviewPageView and adding it to the * overview via [[NIOverview @link NIOverview::view view@endlink] @link NIOverviewView::addPageView: addPageView:@endlink]. */ /** * The sensors used to power the Overview. * * @defgroup Overview-Sensors Sensors */ /** * The primary classes you'll use when dealing with the Overview. * * @defgroup Overview Overview */ /** * The Overview logger. * * @defgroup Overview-Logger Logger */ /** * The pages that are shown in the Overview. * * @defgroup Overview-Pages Pages */ /**@}*/ /** * Log entries for the Overview logger. * * @defgroup Overview-Logger-Entries Log Entries * @ingroup Overview-Logger */ #import "NimbusCore.h" #import "NIOverview.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NIPagingScrollView+Subclassing.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPagingScrollView.h" // Methods that are meant to be subclassed. @interface NIPagingScrollView (Subclassing) // Meant to be subclassed. Default implementations are stubs. - (void)willDisplayPage:(UIView<NIPagingScrollViewPage> *)pageView; - (void)didRecyclePage:(UIView<NIPagingScrollViewPage> *)pageView; - (void)didReloadNumberOfPages; - (void)didChangeCenterPageIndexFrom:(NSInteger)from to:(NSInteger)to; // Meant to be subclassed. - (UIView<NIPagingScrollViewPage> *)loadPageAtIndex:(NSInteger)pageIndex; #pragma mark Accessing Child Views - (UIScrollView *)scrollView; - (NSMutableSet *)visiblePages; // Set of UIView<NIPagingScrollViewPage>* @end // Methods that are not meant to be subclassed. @interface NIPagingScrollView (ProtectedMethods) - (void)setCenterPageIndexIvar:(NSInteger)centerPageIndex; - (void)recyclePageAtIndex:(NSInteger)pageIndex; - (void)displayPageAtIndex:(NSInteger)pageIndex; - (CGFloat)pageScrollableDimension; - (void)layoutVisiblePages; @end /** * Called before the page is about to be shown and after its frame has been set. * * Meant to be subclassed. By default this method does nothing. * * @fn NIPagingScrollView::willDisplayPage: */ /** * Called immediately after the page is removed from the paging scroll view. * * Meant to be subclassed. By default this method does nothing. * * @fn NIPagingScrollView::didRecyclePage: */ /** * Called immediately after the data source has been queried for its number of * pages. * * Meant to be subclassed. By default this method does nothing. * * @fn NIPagingScrollView::didReloadNumberOfPages */ /** * Called when the visible page has changed. * * Meant to be subclassed. By default this method does nothing. * * @fn NIPagingScrollView::didChangeCenterPageIndexFrom:to: */ /** * Called when a page needs to be loaded before it is displayed. * * By default this method asks the data source for the page at the given index. * A subclass may chose to modify the page index using a transformation method * before calling super. * * @fn NIPagingScrollView::loadPageAtIndex: */ /** * Sets the centerPageIndex ivar without side effects. * * @fn NIPagingScrollView::setCenterPageIndexIvar: */ /** * Recycles the page at the given index. * * @fn NIPagingScrollView::recyclePageAtIndex: */ /** * Displays the page at the given index. * * @fn NIPagingScrollView::displayPageAtIndex: */ /** * Returns the page's scrollable dimension. * * This is the width of the paging scroll view for horizontal scroll views, or * the height of the paging scroll view for vertical scroll views. * * @fn NIPagingScrollView::pageScrollableDimension */ /** * Updates the frames of all visible pages based on their page indices. * * @fn NIPagingScrollView::layoutVisiblePages */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NIPagingScrollView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Copyright 2012 Manu Cornet (vertical layouts) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NimbusCore.h" /** * numberOfPages will be this value until reloadData is called. */ extern const NSInteger NIPagingScrollViewUnknownNumberOfPages; /** * The default number of pixels on the side of each page. * * Value: 10 */ extern const CGFloat NIPagingScrollViewDefaultPageMargin; typedef enum { NIPagingScrollViewHorizontal = 0, NIPagingScrollViewVertical, } NIPagingScrollViewType; @protocol NIPagingScrollViewDataSource; @protocol NIPagingScrollViewDelegate; @protocol NIPagingScrollViewPage; @class NIViewRecycler; /** * The NIPagingScrollView class provides a UITableView-like interface for loading pages via a data * source. * * @ingroup NimbusPagingScrollView */ @interface NIPagingScrollView : UIView <UIScrollViewDelegate> #pragma mark Data Source - (void)reloadData; @property (nonatomic, weak) id<NIPagingScrollViewDataSource> dataSource; @property (nonatomic, weak) id<NIPagingScrollViewDelegate> delegate; // It is highly recommended that you use this method to manage view recycling. - (UIView<NIPagingScrollViewPage> *)dequeueReusablePageWithIdentifier:(NSString *)identifier; #pragma mark State - (UIView<NIPagingScrollViewPage> *)centerPageView; @property (nonatomic) NSInteger centerPageIndex; // Use moveToPageAtIndex:animated: to animate to a given page. @property (nonatomic, readonly) NSInteger numberOfPages; #pragma mark Configuring Presentation @property (nonatomic) CGFloat pageMargin; @property (nonatomic) NIPagingScrollViewType type; // Default: NIPagingScrollViewHorizontal #pragma mark Visible Pages - (BOOL)hasNext; - (BOOL)hasPrevious; - (void)moveToNextAnimated:(BOOL)animated; - (void)moveToPreviousAnimated:(BOOL)animated; - (BOOL)moveToPageAtIndex:(NSInteger)pageIndex animated:(BOOL)animated updateVisiblePagesWhileScrolling:(BOOL)updateVisiblePagesWhileScrolling; // Short form for moveToPageAtIndex:pageIndex animated:animated updateVisiblePagesWhileScrolling:NO - (BOOL)moveToPageAtIndex:(NSInteger)pageIndex animated:(BOOL)animated; #pragma mark Rotating the Scroll View - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration; - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration; @end /** * The delegate for NIPagingScrollView. * * @ingroup NimbusPagingScrollView */ @protocol NIPagingScrollViewDelegate <UIScrollViewDelegate> @optional #pragma mark Scrolling and Zooming /** @name [NIPhotoAlbumScrollViewDelegate] Scrolling and Zooming */ /** * The user is scrolling between two photos. */ - (void)pagingScrollViewDidScroll:(NIPagingScrollView *)pagingScrollView; #pragma mark Changing Pages /** @name [NIPagingScrollViewDelegate] Changing Pages */ /** * The current page will change. * * pagingScrollView.centerPageIndex will reflect the old page index, not the new * page index. */ - (void)pagingScrollViewWillChangePages:(NIPagingScrollView *)pagingScrollView; /** * The current page has changed. * * pagingScrollView.centerPageIndex will reflect the changed page index. */ - (void)pagingScrollViewDidChangePages:(NIPagingScrollView *)pagingScrollView; @end /** * The data source for NIPagingScrollView. * * @ingroup NimbusPagingScrollView */ @protocol NIPagingScrollViewDataSource <NSObject> @required #pragma mark Fetching Required Album Information /** @name [NIPagingScrollViewDataSource] Fetching Required Album Information */ /** * Fetches the total number of pages in the scroll view. * * The value returned in this method will be cached by the scroll view until reloadData * is called again. */ - (NSInteger)numberOfPagesInPagingScrollView:(NIPagingScrollView *)pagingScrollView; /** * Fetches a page that will be displayed at the given page index. * * You should always try to reuse pages by calling dequeueReusablePageWithIdentifier: on the * paging scroll view before allocating a new page. */ - (UIView<NIPagingScrollViewPage> *)pagingScrollView:(NIPagingScrollView *)pagingScrollView pageViewForIndex:(NSInteger)pageIndex; @end /** * The protocol that a paging scroll view page should implement. * * By providing a protocol instead of a UIView base class we allow more flexibility when * building pages. * * @ingroup NimbusPagingScrollView */ @protocol NIPagingScrollViewPage <NIRecyclableView> @required /** * The index of this page view. */ @property (nonatomic, assign) NSInteger pageIndex; @optional /** * Called after the page has gone off-screen. * * This method should be used to reset any state information after a page goes off-screen. * For example, in the Nimbus photo viewer we reset the zoom scale so that if the photo * was zoomed in it will fit on the screen again when the user flips back and forth between * two pages. */ - (void)pageDidDisappear; /** * Called when the frame of the page is going to change. * * Use this method to maintain any state that may be affected by the frame changing. * The Nimbus photo viewer uses this method to save and restore the zoom and center * point. This makes the photo always appear to rotate around the center point of the screen * rather than the center of the photo. */ - (void)setFrameAndMaintainState:(CGRect)frame; @end /** @name Data Source */ /** * The data source for this page album view. * * This is the only means by which this paging view acquires any information about the * album to be displayed. * * @fn NIPagingScrollView::dataSource */ /** * Force the view to reload its data by asking the data source for information. * * This must be called at least once after dataSource has been set in order for the view * to gather any presentable information. * * This method is cheap because we only fetch new information about the currently displayed * pages. If the number of pages shrinks then the current center page index will be decreased * accordingly. * * @fn NIPagingScrollView::reloadData */ /** * Dequeues a reusable page from the set of recycled pages. * * If no pages have been recycled for the given identifier then this will return nil. * In this case it is your responsibility to create a new page. * * @fn NIPagingScrollView::dequeueReusablePageWithIdentifier: */ /** * The delegate for this paging view. * * Any user interactions or state changes are sent to the delegate through this property. * * @fn NIPagingScrollView::delegate */ /** @name Configuring Presentation */ /** * The number of pixels on either side of each page. * * The space between each page will be 2x this value. * * By default this is NIPagingScrollViewDefaultPageMargin. * * @fn NIPagingScrollView::pageMargin */ /** * The type of paging scroll view to display. * * This property allows you to configure whether you want a horizontal or vertical paging scroll * view. You should set this property before you present the scroll view and not modify it after. * * By default this is NIPagingScrollViewHorizontal. * * @fn NIPagingScrollView::type */ /** @name State */ /** * The current center page view. * * If no pages exist then this will return nil. * * @fn NIPagingScrollView::centerPageView */ /** * The current center page index. * * This is a zero-based value. If you intend to use this in a label such as "page ## of n" be * sure to add one to this value. * * Setting this value directly will center the new page without any animation. * * @fn NIPagingScrollView::centerPageIndex */ /** * Change the center page index with optional animation. * * This method is deprecated in favor of * @link NIPagingScrollView::moveToPageAtIndex:animated: moveToPageAtIndex:animated:@endlink * * @fn NIPagingScrollView::setCenterPageIndex:animated: */ /** * The total number of pages in this paging view, as gathered from the data source. * * This value is cached after reloadData has been called. * * Until reloadData is called the first time, numberOfPages will be * NIPagingScrollViewUnknownNumberOfPages. * * @fn NIPagingScrollView::numberOfPages */ /** @name Changing the Visible Page */ /** * Returns YES if there is a next page. * * @fn NIPagingScrollView::hasNext */ /** * Returns YES if there is a previous page. * * @fn NIPagingScrollView::hasPrevious */ /** * Move to the next page if there is one. * * @fn NIPagingScrollView::moveToNextAnimated: */ /** * Move to the previous page if there is one. * * @fn NIPagingScrollView::moveToPreviousAnimated: */ /** * Move to the given page index with optional animation. * * @returns NO if a page change animation is already in effect and we couldn't change the page * again. * @fn NIPagingScrollView::moveToPageAtIndex:animated: */ /** * Move to the given page index with optional animation and option to enable page updates while * scrolling. * * NOTE: Passing YES for moveToPageAtIndex:animated:updateVisiblePagesWhileScrolling will cause * every page from the present page to the destination page to be loaded. This has the potential to * cause choppy animations. * * @param updateVisiblePagesWhileScrolling If YES, will query the data source for any pages * that become visible while the animation occurs. * @returns NO if a page change animation is already in effect and we couldn't change the page * again. * @fn NIPagingScrollView::moveToPageAtIndex:animated:updateVisiblePagesWhileScrolling: */ /** @name Rotating the Scroll View */ /** * Stores the current state of the scroll view in preparation for rotation. * * This must be called in conjunction with willAnimateRotationToInterfaceOrientation:duration: * in the methods by the same name from the view controller containing this view. * * @fn NIPagingScrollView::willRotateToInterfaceOrientation:duration: */ /** * Updates the frame of the scroll view while maintaining the current visible page's state. * * @fn NIPagingScrollView::willAnimateRotationToInterfaceOrientation:duration: */ /** @name Subclassing */ /** * The internal scroll view. * * Meant to be used by subclasses only. * * @fn NIPagingScrollView::pagingScrollView */ /** * The set of currently visible pages. * * Meant to be used by subclasses only. * * @fn NIPagingScrollView::visiblePages */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NIPagingScrollView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Copyright 2012 Manu Cornet (vertical layouts) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPagingScrollView.h" #import "NIPagingScrollView+Subclassing.h" #import "NimbusCore.h" #import <objc/runtime.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif const NSInteger NIPagingScrollViewUnknownNumberOfPages = -1; const CGFloat NIPagingScrollViewDefaultPageMargin = 10; @implementation NIPagingScrollView { NIViewRecycler* _viewRecycler; UIScrollView* _scrollView; NSMutableSet* _visiblePages; // Animating to Pages NSInteger _animatingToPageIndex; BOOL _isKillingAnimation; NSInteger _queuedAnimationPageIndex; BOOL _shouldUpdateVisiblePagesWhileScrolling; // Rotation State NSInteger _firstVisiblePageIndexBeforeRotation; CGFloat _percentScrolledIntoFirstVisiblePage; } - (void)commonInit { // Default state. self.pageMargin = NIPagingScrollViewDefaultPageMargin; self.type = NIPagingScrollViewHorizontal; // Internal state _animatingToPageIndex = -1; _firstVisiblePageIndexBeforeRotation = -1; _percentScrolledIntoFirstVisiblePage = -1; _centerPageIndex = -1; _numberOfPages = NIPagingScrollViewUnknownNumberOfPages; _viewRecycler = [[NIViewRecycler alloc] init]; // The internal scroll view that powers this paging scroll view. _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds]; _scrollView.pagingEnabled = YES; _scrollView.scrollsToTop = NO; _scrollView.autoresizingMask = UIViewAutoresizingFlexibleDimensions; _scrollView.delegate = self; _scrollView.showsVerticalScrollIndicator = NO; _scrollView.showsHorizontalScrollIndicator = NO; [self addSubview:_scrollView]; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self commonInit]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if ((self = [super initWithCoder:aDecoder])) { [self commonInit]; } return self; } #pragma mark - Page Layout // The following three methods are from Apple's ImageScrollView example application and have // been used here because they are well-documented and concise. - (CGRect)frameForPagingScrollView { CGRect frame = self.bounds; if (NIPagingScrollViewHorizontal == self.type) { // We make the paging scroll view a little bit wider on the side edges so that there // there is space between the pages when flipping through them. frame = CGRectInset(frame, -self.pageMargin, 0); } else if (NIPagingScrollViewVertical == self.type) { frame = CGRectInset(frame, 0, -self.pageMargin); } return frame; } - (CGRect)frameForPageAtIndex:(NSInteger)pageIndex { // We have to use our paging scroll view's bounds, not frame, to calculate the page // placement. When the device is in landscape orientation, the frame will still be in // portrait because the pagingScrollView is the root view controller's view, so its // frame is in window coordinate space, which is never rotated. Its bounds, however, // will be in landscape because it has a rotation transform applied. CGRect bounds = _scrollView.bounds; CGRect pageFrame = bounds; if (NIPagingScrollViewHorizontal == self.type) { pageFrame.origin.x = (bounds.size.width * pageIndex); // We need to counter the extra spacing added to the paging scroll view in // frameForPagingScrollView. pageFrame = CGRectInset(pageFrame, self.pageMargin, 0); } else if (NIPagingScrollViewVertical == self.type) { pageFrame.origin.y = (bounds.size.height * pageIndex); pageFrame = CGRectInset(pageFrame, 0, self.pageMargin); } return pageFrame; } - (CGSize)contentSizeForPagingScrollView { // We use the paging scroll view's bounds to calculate the contentSize, for the same reason // outlined above. CGRect bounds = _scrollView.bounds; if (NIPagingScrollViewHorizontal == self.type) { return CGSizeMake(bounds.size.width * self.numberOfPages, bounds.size.height); } else if (NIPagingScrollViewVertical == self.type) { return CGSizeMake(bounds.size.width, bounds.size.height * self.numberOfPages); } return CGSizeZero; } - (CGPoint)contentOffsetFromPageOffset:(CGPoint)offset { if (NIPagingScrollViewHorizontal == self.type) { offset.x -= self.pageMargin; } else if (NIPagingScrollViewVertical == self.type) { offset.y -= self.pageMargin; } return offset; } - (CGFloat)pageScrollableDimension { if (NIPagingScrollViewHorizontal == self.type) { return _scrollView.bounds.size.width; } else if (NIPagingScrollViewVertical == self.type) { return _scrollView.bounds.size.height; } return 0; } - (CGPoint)contentOffsetFromOffset:(CGFloat)offset { if (NIPagingScrollViewHorizontal == self.type) { return CGPointMake(offset, 0); } else if (NIPagingScrollViewVertical == self.type) { return CGPointMake(0, offset); } return CGPointMake(0, 0); } - (CGFloat)scrolledPageOffset { if (NIPagingScrollViewHorizontal == self.type) { return _scrollView.contentOffset.x; } else if (NIPagingScrollViewVertical == self.type) { return _scrollView.contentOffset.y; } return 0; } #pragma mark - Visible Page Management - (BOOL)isDisplayingPageForIndex:(NSInteger)pageIndex { BOOL foundPage = NO; // There will never be more than 3 visible pages in this array, so this lookup is // effectively O(C) constant time. for (UIView <NIPagingScrollViewPage>* page in _visiblePages) { if (page.pageIndex == pageIndex) { foundPage = YES; break; } } return foundPage; } - (NSInteger)currentVisiblePageIndex { CGPoint contentOffset = _scrollView.contentOffset; CGSize boundsSize = _scrollView.bounds.size; if (NIPagingScrollViewHorizontal == self.type) { // Whatever image is currently displayed in the center of the screen is the currently // visible image. return NIBoundi((NSInteger)(floorf((contentOffset.x + boundsSize.width / 2) / boundsSize.width) + 0.5f), 0, self.numberOfPages - 1); } else if (NIPagingScrollViewVertical == self.type) { return NIBoundi((NSInteger)(floorf((contentOffset.y + boundsSize.height / 2) / boundsSize.height) + 0.5f), 0, self.numberOfPages - 1); } return 0; } - (NSRange)rangeOfVisiblePages { if (0 >= self.numberOfPages) { return NSMakeRange(0, 0); } NSInteger currentVisiblePageIndex = [self currentVisiblePageIndex]; NSInteger firstVisiblePageIndex = NIBoundi(currentVisiblePageIndex - 1, 0, self.numberOfPages - 1); NSInteger lastVisiblePageIndex = NIBoundi(currentVisiblePageIndex + 1, 0, self.numberOfPages - 1); return NSMakeRange(firstVisiblePageIndex, lastVisiblePageIndex - firstVisiblePageIndex + 1); } - (void)willDisplayPage:(UIView<NIPagingScrollViewPage> *)pageView atIndex:(NSInteger)pageIndex { pageView.pageIndex = pageIndex; pageView.frame = [self frameForPageAtIndex:pageIndex]; [self willDisplayPage:pageView]; } - (void)resetPage:(id<NIPagingScrollViewPage>)page { if ([page respondsToSelector:@selector(pageDidDisappear)]) { [page pageDidDisappear]; } } - (void)resetSurroundingPages { for (id<NIPagingScrollViewPage> page in _visiblePages) { if (page.pageIndex != self.centerPageIndex) { [self resetPage:page]; } } } - (UIView<NIPagingScrollViewPage> *)dequeueReusablePageWithIdentifier:(NSString *)identifier { NIDASSERT(nil != identifier); if (nil == identifier) { return nil; } return (UIView<NIPagingScrollViewPage> *)[_viewRecycler dequeueReusableViewWithIdentifier:identifier]; } - (UIView<NIPagingScrollViewPage> *)loadPageAtIndex:(NSInteger)pageIndex { UIView<NIPagingScrollViewPage>* page = [self.dataSource pagingScrollView:self pageViewForIndex:pageIndex]; NIDASSERT([page isKindOfClass:[UIView class]]); NIDASSERT([page conformsToProtocol:@protocol(NIPagingScrollViewPage)]); if (nil == page || ![page isKindOfClass:[UIView class]] || ![page conformsToProtocol:@protocol(NIPagingScrollViewPage)]) { // Bail out! This page is malformed. return nil; } return page; } - (void)displayPageAtIndex:(NSInteger)pageIndex { UIView<NIPagingScrollViewPage>* page = [self loadPageAtIndex:pageIndex]; if (nil == page) { return; } // This will only be called once, before the page is shown. [self willDisplayPage:page atIndex:pageIndex]; [_scrollView addSubview:page]; [_visiblePages addObject:page]; } - (void)recyclePageAtIndex:(NSInteger)pageIndex { for (UIView<NIPagingScrollViewPage>* page in [_visiblePages copy]) { if (page.pageIndex == pageIndex) { [_viewRecycler recycleView:page]; [page removeFromSuperview]; [self didRecyclePage:page]; [_visiblePages removeObject:page]; } } } - (void)updateVisiblePagesShouldNotifyDelegate:(BOOL)shouldNotifyDelegate { // Before updating _centerPageIndex, notify delegate if (shouldNotifyDelegate && (self.numberOfPages > 0) && ([self currentVisiblePageIndex] != self.centerPageIndex) && [self.delegate respondsToSelector:@selector(pagingScrollViewWillChangePages:)]) { [self.delegate pagingScrollViewWillChangePages:self]; } NSRange rangeOfVisiblePages = [self rangeOfVisiblePages]; // Recycle no-longer-visible pages. We copy _visiblePages because we may modify it while we're // iterating over it. for (UIView<NIPagingScrollViewPage>* page in [_visiblePages copy]) { if (!NSLocationInRange(page.pageIndex, rangeOfVisiblePages)) { [_viewRecycler recycleView:page]; [page removeFromSuperview]; [self didRecyclePage:page]; [_visiblePages removeObject:page]; } } NSInteger oldCenterPageIndex = self.centerPageIndex; if (self.numberOfPages > 0) { _centerPageIndex = [self currentVisiblePageIndex]; [self didChangeCenterPageIndexFrom:oldCenterPageIndex to:_centerPageIndex]; // Prioritize displaying the currently visible page. if (![self isDisplayingPageForIndex:_centerPageIndex]) { [self displayPageAtIndex:_centerPageIndex]; } // Add missing pages. for (int pageIndex = rangeOfVisiblePages.location; pageIndex < (NSInteger)NSMaxRange(rangeOfVisiblePages); ++pageIndex) { if (![self isDisplayingPageForIndex:pageIndex]) { [self displayPageAtIndex:pageIndex]; } } } else { _centerPageIndex = -1; } if (shouldNotifyDelegate && oldCenterPageIndex != _centerPageIndex && [self.delegate respondsToSelector:@selector(pagingScrollViewDidChangePages:)]) { [self.delegate pagingScrollViewDidChangePages:self]; } } - (void)layoutVisiblePages { for (UIView<NIPagingScrollViewPage>* page in _visiblePages) { CGRect pageFrame = [self frameForPageAtIndex:page.pageIndex]; if ([page respondsToSelector:@selector(setFrameAndMaintainState:)]) { [page setFrameAndMaintainState:pageFrame]; } else { [page setFrame:pageFrame]; } } } #pragma mark - UIView - (void)setFrame:(CGRect)frame { // We have to modify this method because it eventually leads to changing the content offset // programmatically. When this happens we end up getting a scrollViewDidScroll: message // during which we do not want to modify the visible pages because this is handled elsewhere. [super setFrame:frame]; _scrollView.contentSize = [self contentSizeForPagingScrollView]; [self layoutVisiblePages]; } #pragma mark - UIScrollViewDelegate - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { [self updateVisiblePagesShouldNotifyDelegate:YES]; _isKillingAnimation = NO; if ([self.delegate respondsToSelector:_cmd]) { [self.delegate scrollViewWillBeginDragging:scrollView]; } } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if ([scrollView isTracking] && [scrollView isDragging]) { if ([self.delegate respondsToSelector:@selector(pagingScrollViewDidScroll:)]) { [self.delegate pagingScrollViewDidScroll:self]; } } if (_shouldUpdateVisiblePagesWhileScrolling && ![scrollView isTracking] && ![scrollView isDragging]) { [self updateVisiblePagesShouldNotifyDelegate:YES]; } if ([self.delegate respondsToSelector:_cmd]) { [self.delegate scrollViewDidScroll:scrollView]; } if (_isKillingAnimation) { // The content size is calculated based on the number of pages and the scroll view frame. CGPoint offset = [self frameForPageAtIndex:_centerPageIndex].origin; offset = [self contentOffsetFromPageOffset:offset]; _scrollView.contentOffset = offset; } } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { _isKillingAnimation = NO; if (!decelerate) { [self updateVisiblePagesShouldNotifyDelegate:YES]; [self resetSurroundingPages]; } if ([self.delegate respondsToSelector:_cmd]) { [self.delegate scrollViewDidEndDragging:scrollView willDecelerate:decelerate]; } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [self updateVisiblePagesShouldNotifyDelegate:YES]; [self resetSurroundingPages]; if ([self.delegate respondsToSelector:_cmd]) { [self.delegate scrollViewDidEndDecelerating:scrollView]; } } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { [self didAnimateToPage:_animatingToPageIndex]; if ([self.delegate respondsToSelector:_cmd]) { [self.delegate scrollViewDidEndScrollingAnimation:scrollView]; } } #pragma mark - Forward UIScrollViewDelegate Methods - (BOOL)shouldForwardSelectorToDelegate:(SEL)aSelector { struct objc_method_description description; // Only forward the selector if it's part of the UIScrollViewDelegate protocol. description = protocol_getMethodDescription(@protocol(UIScrollViewDelegate), aSelector, NO, YES); BOOL isSelectorInScrollViewDelegate = (description.name != NULL && description.types != NULL); return (isSelectorInScrollViewDelegate && [self.delegate respondsToSelector:aSelector]); } - (BOOL)respondsToSelector:(SEL)aSelector { if ([super respondsToSelector:aSelector] == YES) { return YES; } else { return [self shouldForwardSelectorToDelegate:aSelector]; } } - (id)forwardingTargetForSelector:(SEL)aSelector { if ([self shouldForwardSelectorToDelegate:aSelector]) { return self.delegate; } else { return nil; } } #pragma mark - Subclassing - (void)willDisplayPage:(UIView<NIPagingScrollViewPage> *)pageView { // No-op. } - (void)didRecyclePage:(UIView<NIPagingScrollViewPage> *)pageView { // No-op } - (void)didReloadNumberOfPages { // No-op } - (void)didChangeCenterPageIndexFrom:(NSInteger)from to:(NSInteger)to { // No-op } - (void)setCenterPageIndexIvar:(NSInteger)centerPageIndex { _centerPageIndex = centerPageIndex; } #pragma mark - Public - (void)reloadData { _animatingToPageIndex = -1; NIDASSERT(nil != _dataSource); // Remove any visible pages from the view before we release the sets. for (UIView<NIPagingScrollViewPage>* page in _visiblePages) { [_viewRecycler recycleView:page]; [(UIView *)page removeFromSuperview]; [self didRecyclePage:page]; } _visiblePages = nil; // If there is no data source then we can't do anything particularly interesting. if (nil == _dataSource) { _scrollView.contentSize = self.bounds.size; _scrollView.contentOffset = CGPointZero; // May as well just get rid of all the views then. [_viewRecycler removeAllViews]; return; } _visiblePages = [[NSMutableSet alloc] init]; // Cache the number of pages. _numberOfPages = [_dataSource numberOfPagesInPagingScrollView:self]; _scrollView.frame = [self frameForPagingScrollView]; _scrollView.contentSize = [self contentSizeForPagingScrollView]; [self didReloadNumberOfPages]; NSInteger oldCenterPageIndex = _centerPageIndex; if (oldCenterPageIndex >= 0) { _centerPageIndex = NIBoundi(_centerPageIndex, 0, self.numberOfPages - 1); if (![_scrollView isTracking] && ![_scrollView isDragging]) { // The content size is calculated based on the number of pages and the scroll view frame. CGPoint offset = [self frameForPageAtIndex:_centerPageIndex].origin; offset = [self contentOffsetFromPageOffset:offset]; _scrollView.contentOffset = offset; _isKillingAnimation = YES; } } // Begin requesting the page information from the data source. [self updateVisiblePagesShouldNotifyDelegate:NO]; } - (void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration { // Here, our pagingScrollView bounds have not yet been updated for the new interface // orientation. This is a good place to calculate the content offset that we will // need in the new orientation. CGFloat offset = [self scrolledPageOffset]; CGFloat pageScrollableDimension = [self pageScrollableDimension]; if (offset >= 0) { _firstVisiblePageIndexBeforeRotation = (NSInteger)floorf(offset / pageScrollableDimension); _percentScrolledIntoFirstVisiblePage = ((offset - (_firstVisiblePageIndexBeforeRotation * pageScrollableDimension)) / pageScrollableDimension); } else { _firstVisiblePageIndexBeforeRotation = 0; _percentScrolledIntoFirstVisiblePage = offset / pageScrollableDimension; } } - (void)willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration { // Recalculate contentSize based on current orientation. _scrollView.contentSize = [self contentSizeForPagingScrollView]; [self layoutVisiblePages]; // Adjust contentOffset to preserve page location based on values collected prior to location. CGFloat pageScrollableDimension = [self pageScrollableDimension]; CGFloat newOffset = ((_firstVisiblePageIndexBeforeRotation * pageScrollableDimension) + (_percentScrolledIntoFirstVisiblePage * pageScrollableDimension)); _scrollView.contentOffset = [self contentOffsetFromOffset:newOffset]; } - (BOOL)hasNext { return (self.centerPageIndex < self.numberOfPages - 1); } - (BOOL)hasPrevious { return self.centerPageIndex > 0; } - (void)didAnimateToPage:(NSInteger)pageIndex { _shouldUpdateVisiblePagesWhileScrolling = NO; _animatingToPageIndex = -1; if (_queuedAnimationPageIndex >= 0 && _queuedAnimationPageIndex != pageIndex) { [self moveToPageAtIndex:_queuedAnimationPageIndex animated:YES]; return; } // Reset the content offset once the animation completes, just to be sure that the // viewer sits on a page bounds even if we rotate the device while animating. CGPoint offset = [self frameForPageAtIndex:pageIndex].origin; offset = [self contentOffsetFromPageOffset:offset]; _scrollView.contentOffset = offset; [self updateVisiblePagesShouldNotifyDelegate:YES]; } - (BOOL)moveToPageAtIndex:(NSInteger)pageIndex animated:(BOOL)animated { return [self moveToPageAtIndex:pageIndex animated:animated updateVisiblePagesWhileScrolling:NO]; } - (BOOL)moveToPageAtIndex:(NSInteger)pageIndex animated:(BOOL)animated updateVisiblePagesWhileScrolling:(BOOL)updateVisiblePagesWhileScrolling { if (_animatingToPageIndex >= 0) { // Don't allow re-entry for sliding animations. _queuedAnimationPageIndex = pageIndex; return NO; } _shouldUpdateVisiblePagesWhileScrolling = updateVisiblePagesWhileScrolling; _isKillingAnimation = NO; _queuedAnimationPageIndex = -1; CGPoint offset = [self frameForPageAtIndex:pageIndex].origin; offset = [self contentOffsetFromPageOffset:offset]; // The paging scroll view won't actually animate if the offsets are identical. animated = animated && !CGPointEqualToPoint(offset, _scrollView.contentOffset); if (animated) { _animatingToPageIndex = pageIndex; } [_scrollView setContentOffset:offset animated:animated]; if (!animated) { [self resetSurroundingPages]; [self didAnimateToPage:pageIndex]; } return YES; } - (void)moveToNextAnimated:(BOOL)animated { if ([self hasNext]) { NSInteger pageIndex = self.centerPageIndex + 1; [self moveToPageAtIndex:pageIndex animated:animated]; } } - (void)moveToPreviousAnimated:(BOOL)animated { if ([self hasPrevious]) { NSInteger pageIndex = self.centerPageIndex - 1; [self moveToPageAtIndex:pageIndex animated:animated]; } } - (UIView<NIPagingScrollViewPage> *)centerPageView { for (UIView<NIPagingScrollViewPage>* page in _visiblePages) { if (page.pageIndex == self.centerPageIndex) { return page; } } return nil; } - (void)setCenterPageIndex:(NSInteger)centerPageIndex { [self moveToPageAtIndex:centerPageIndex animated:NO]; } - (void)setPageMargin:(CGFloat)pageMargin { _pageMargin = pageMargin; [self setNeedsLayout]; } - (void)setType:(NIPagingScrollViewType)type { if (_type != type) { _type = type; _scrollView.scrollsToTop = (type == NIPagingScrollViewVertical); } } - (UIScrollView *)scrollView { return _scrollView; } - (NSMutableSet *)visiblePages { return _visiblePages; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NIPagingScrollViewPage.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> #import "NIPagingScrollView.h" /** * A skeleton implementation of a page view. * * This view simply implements the required properties of NIPagingScrollViewPage. * * @ingroup NimbusPagingScrollView */ @interface NIPagingScrollViewPage : NIRecyclableView <NIPagingScrollViewPage> @property (nonatomic) NSInteger pageIndex; @end /** * Use NIPagingScrollViewPage instead. * * This class will be deleted after February 28, 2014. * * @ingroup NimbusPagingScrollView */ __NI_DEPRECATED_METHOD @interface NIPageView : NIPagingScrollViewPage @end /** * The page index. * * @fn NIPageView::pageIndex */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NIPagingScrollViewPage.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPagingScrollViewPage.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIPagingScrollViewPage @end @implementation NIPageView @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/pagingscrollview/src/NimbusPagingScrollView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> /** * @defgroup NimbusPagingScrollView Nimbus Paging Scroll View * @{ * * <div id="github" feature="pagingscrollview"></div> * * A paging scroll view is a UIScrollView that scrolls horizontally and shows a series of * pages that are efficiently recycled. * * The Nimbus paging scroll view is powered by a datasource that allows you to separate the * data from the view. This makes it easy to efficiently recycle pages and only create as many * pages of content as may be visible at any given point in time. Nimbus' implementation also * provides helpful features such as keeping the center page centered when the device changes * orientation. * * Paging scroll views are commonly used in many iOS applications. For example, Nimbus' Photos * feature uses a paging scroll view to power its NIPhotoAlbumScrollView. * * <h2>Building a Component with NIPagingScrollView</h2> * * NIPagingScrollView works much like a UITableView in that you must implement a data source * and optionally a delegate. The data source fetches information about the contents of the * paging scroll view, such as the total number of pages and the view for a given page when it * is required. The views that you return for pages must conform to the NIPagingScrollViewPage * protocol. This is similar to UITableViewCell, but rather than subclass a view you can simply * implement a protocol. If you would prefer not to implement the protocol, you can subclass * NIPageView which implements the required methods of NIPagingScrollViewPage. */ /**@}*/ #import "NIPagingScrollView.h" #import "NIPagingScrollViewPage.h" #import "NimbusCore.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoAlbumScrollView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPhotoScrollViewDelegate.h" #import "NIPhotoAlbumScrollViewDataSource.h" #import "NIPhotoAlbumScrollViewDelegate.h" #import "NimbusPagingScrollView.h" #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> /** * A paged scroll view that shows a collection of photos. * * @ingroup NimbusPhotos * * This view provides a light-weight implementation of a photo viewer, complete with * pinch-to-zoom and swiping to change photos. It is designed to perform well with * large sets of photos and large images that are loaded from either the network or * disk. * * It is intended for this view to be used in conjunction with a view controller that * implements the data source protocol and presents any required chrome. * * @see NIToolbarPhotoViewController */ @interface NIPhotoAlbumScrollView : NIPagingScrollView <NIPhotoScrollViewDelegate> #pragma mark Data Source // For use in your pagingScrollView:pageForIndex: data source implementation. - (UIView<NIPagingScrollViewPage> *)pagingScrollView:(NIPagingScrollView *)pagingScrollView pageViewForIndex:(NSInteger)pageIndex; @property (nonatomic, weak) id<NIPhotoAlbumScrollViewDataSource> dataSource; @property (nonatomic, weak) id<NIPhotoAlbumScrollViewDelegate> delegate; #pragma mark Configuring Functionality @property (nonatomic, assign, getter=isZoomingEnabled) BOOL zoomingIsEnabled; @property (nonatomic, assign, getter=isZoomingAboveOriginalSizeEnabled) BOOL zoomingAboveOriginalSizeIsEnabled; @property (nonatomic, strong) UIColor* photoViewBackgroundColor; #pragma mark Configuring Presentation @property (nonatomic, strong) UIImage* loadingImage; #pragma mark Notifying the View of Loaded Photos - (void)didLoadPhoto: (UIImage *)image atIndex: (NSInteger)photoIndex photoSize: (NIPhotoScrollViewPhotoSize)photoSize; @end /** @name Data Source */ /** * The data source for this photo album view. * * This is the only means by which this photo album view acquires any information about the * album to be displayed. * * @fn NIPhotoAlbumScrollView::dataSource */ /** * Use this method in your implementation of NIPhotoAlbumScrollViewDataSource's * pagingScrollView:pageForIndex:. * * Example: * @code - (id<NIPagingScrollViewPage>)pagingScrollView:(NIPagingScrollView *)pagingScrollView pageForIndex:(NSInteger)pageIndex { return [self.photoAlbumView pagingScrollView:pagingScrollView pageForIndex:pageIndex]; } @endcode * * Automatically uses the paging scroll view's page recycling methods and creates * NIPhotoScrollViews as needed. * * @fn NIPhotoAlbumScrollView::pagingScrollView:pageForIndex: */ /** * The delegate for this photo album view. * * Any user interactions or state changes are sent to the delegate through this property. * * @fn NIPhotoAlbumScrollView::delegate */ /** @name Configuring Functionality */ /** * Whether zooming is enabled or not. * * Regardless of whether this is enabled, only original-sized images will be zoomable. * This is because we often don't know how large the final image is so we can't * calculate min and max zoom amounts correctly. * * By default this is YES. * * @fn NIPhotoAlbumScrollView::zoomingIsEnabled */ /** * Whether small photos can be zoomed at least until they fit the screen. * * @see NIPhotoScrollView::zoomingAboveOriginalSizeIsEnabled * * By default this is YES. * * @fn NIPhotoAlbumScrollView::zoomingAboveOriginalSizeIsEnabled */ /** * The background color of each photo's view. * * By default this is [UIColor blackColor]. * * @fn NIPhotoAlbumScrollView::photoViewBackgroundColor */ /** @name Configuring Presentation */ /** * An image that is displayed while the photo is loading. * * This photo will be presented if no image is returned in the data source's implementation * of photoAlbumScrollView:photoAtIndex:photoSize:isLoading:. * * Zooming is disabled when showing a loading image, regardless of the state of zoomingIsEnabled. * * By default this is nil. * * @fn NIPhotoAlbumScrollView::loadingImage */ /** @name Notifying the View of Loaded Photos */ /** * Notify the scroll view that a photo has been loaded at a given index. * * You should notify the completed loading of thumbnails as well. Calling this method * is fairly lightweight and will only update the images of the visible pages. Err on the * side of calling this method too much rather than too little. * * The photo at the given index will only be replaced with the given image if photoSize * is of a higher quality than the currently-displayed photo's size. * * @fn NIPhotoAlbumScrollView::didLoadPhoto:atIndex:photoSize: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoAlbumScrollView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPhotoAlbumScrollView.h" #import "NIPagingScrollView+Subclassing.h" #import "NIPhotoScrollView.h" #import "NIPhotoAlbumScrollViewDataSource.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIPhotoAlbumScrollView { // Configurable Properties UIImage* _loadingImage; BOOL _zoomingIsEnabled; BOOL _zoomingAboveOriginalSizeIsEnabled; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { // Default state. self.zoomingIsEnabled = YES; self.zoomingAboveOriginalSizeIsEnabled = YES; } return self; } - (void)setBackgroundColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; self.scrollView.backgroundColor = backgroundColor; } - (void)notifyDelegatePhotoDidLoadAtIndex:(NSInteger)photoIndex { if (photoIndex == (self.centerPageIndex + 1) && [self.delegate respondsToSelector:@selector(photoAlbumScrollViewDidLoadNextPhoto:)]) { [self.delegate photoAlbumScrollViewDidLoadNextPhoto:self]; } else if (photoIndex == (self.centerPageIndex - 1) && [self.delegate respondsToSelector:@selector(photoAlbumScrollViewDidLoadPreviousPhoto:)]) { [self.delegate photoAlbumScrollViewDidLoadPreviousPhoto:self]; } } #pragma mark - Visible Page Management - (void)willDisplayPage:(NIPhotoScrollView *)page { // When we ask the data source for the image we expect the following to happen: // 1) If the data source has any image at this index, it should return it and set the // photoSize accordingly. // 2) If the returned photo is not the highest quality available, the data source should // start loading the high quality photo and set isLoading to YES. // 3) If no photo was available, then the data source should start loading the photo // at its highest available quality and nil should be returned. The loadingImage property // will be displayed until the image is loaded. isLoading should be set to YES. NIPhotoScrollViewPhotoSize photoSize = NIPhotoScrollViewPhotoSizeUnknown; BOOL isLoading = NO; CGSize originalPhotoDimensions = CGSizeZero; UIImage* image = [self.dataSource photoAlbumScrollView: self photoAtIndex: page.pageIndex photoSize: &photoSize isLoading: &isLoading originalPhotoDimensions: &originalPhotoDimensions]; page.photoDimensions = originalPhotoDimensions; page.loading = isLoading; if (nil == image) { page.zoomingIsEnabled = NO; [page setImage:self.loadingImage photoSize:NIPhotoScrollViewPhotoSizeUnknown]; } else { BOOL updateImage = photoSize > page.photoSize; if (updateImage) { [page setImage:image photoSize:photoSize]; } // Configure this after the image is set otherwise if the page's image isn't there // e.g. (after prepareForReuse), zooming will always be disabled page.zoomingIsEnabled = ([self isZoomingEnabled] && (NIPhotoScrollViewPhotoSizeOriginal == photoSize)); if (updateImage && NIPhotoScrollViewPhotoSizeOriginal == photoSize) { [self notifyDelegatePhotoDidLoadAtIndex:page.pageIndex]; } } } - (void)didRecyclePage:(UIView<NIPagingScrollViewPage> *)page { // Give the data source the opportunity to kill any asynchronous operations for this // now-recycled page. if ([self.dataSource respondsToSelector: @selector(photoAlbumScrollView:stopLoadingPhotoAtIndex:)]) { [self.dataSource photoAlbumScrollView: self stopLoadingPhotoAtIndex: page.pageIndex]; } } #pragma mark - NIPhotoScrollViewDelegate - (void)photoScrollViewDidDoubleTapToZoom: (NIPhotoScrollView *)photoScrollView didZoomIn: (BOOL)didZoomIn { if ([self.delegate respondsToSelector:@selector(photoAlbumScrollView:didZoomIn:)]) { [self.delegate photoAlbumScrollView:self didZoomIn:didZoomIn]; } } #pragma mark - Public - (UIView<NIPagingScrollViewPage> *)pagingScrollView:(NIPagingScrollView *)pagingScrollView pageViewForIndex:(NSInteger)pageIndex { UIView<NIPagingScrollViewPage>* pageView = nil; NSString* reuseIdentifier = @"photo"; pageView = [pagingScrollView dequeueReusablePageWithIdentifier:reuseIdentifier]; if (nil == pageView) { pageView = [[NIPhotoScrollView alloc] init]; pageView.reuseIdentifier = reuseIdentifier; pageView.backgroundColor = self.photoViewBackgroundColor; } NIPhotoScrollView* photoScrollView = (NIPhotoScrollView *)pageView; photoScrollView.photoScrollViewDelegate = self; photoScrollView.zoomingAboveOriginalSizeIsEnabled = [self isZoomingAboveOriginalSizeEnabled]; return pageView; } - (void)didLoadPhoto: (UIImage *)image atIndex: (NSInteger)pageIndex photoSize: (NIPhotoScrollViewPhotoSize)photoSize { // This modifies the UI and therefor MUST be executed on the main thread. NIDASSERT([NSThread isMainThread]); for (NIPhotoScrollView* page in self.visiblePages) { if (page.pageIndex == pageIndex) { // Only replace the photo if it's of a higher quality than one we're already showing. if (photoSize > page.photoSize) { page.loading = NO; [page setImage:image photoSize:photoSize]; page.zoomingIsEnabled = ([self isZoomingEnabled] && (NIPhotoScrollViewPhotoSizeOriginal == photoSize)); // Notify the delegate that the photo has been loaded. if (NIPhotoScrollViewPhotoSizeOriginal == photoSize) { [self notifyDelegatePhotoDidLoadAtIndex:pageIndex]; } } break; } } } - (void)setZoomingAboveOriginalSizeIsEnabled:(BOOL)enabled { _zoomingAboveOriginalSizeIsEnabled = enabled; for (NIPhotoScrollView* page in self.visiblePages) { page.zoomingAboveOriginalSizeIsEnabled = enabled; } } - (void)setPhotoViewBackgroundColor:(UIColor *)photoViewBackgroundColor { if (_photoViewBackgroundColor != photoViewBackgroundColor) { _photoViewBackgroundColor = photoViewBackgroundColor; for (UIView<NIPagingScrollViewPage>* page in self.visiblePages) { page.backgroundColor = photoViewBackgroundColor; } } } - (BOOL)hasNext { return (self.centerPageIndex < self.numberOfPages - 1); } - (BOOL)hasPrevious { return self.centerPageIndex > 0; } - (id<NIPhotoAlbumScrollViewDataSource>)dataSource { NIDASSERT([[super dataSource] conformsToProtocol:@protocol(NIPhotoAlbumScrollViewDataSource)]); return (id<NIPhotoAlbumScrollViewDataSource>)[super dataSource]; } - (void)setDataSource:(id<NIPhotoAlbumScrollViewDataSource>)dataSource { [super setDataSource:(id<NIPagingScrollViewDataSource>)dataSource]; } - (id<NIPhotoAlbumScrollViewDelegate>)delegate { id<NIPagingScrollViewDelegate> superDelegate = [super delegate]; NIDASSERT(nil == superDelegate || [superDelegate conformsToProtocol:@protocol(NIPhotoAlbumScrollViewDelegate)]); return (id<NIPhotoAlbumScrollViewDelegate>)superDelegate; } - (void)setDelegate:(id<NIPhotoAlbumScrollViewDelegate>)delegate { [super setDelegate:(id<NIPhotoAlbumScrollViewDelegate>)delegate]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoAlbumScrollViewDataSource.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPhotoScrollViewPhotoSize.h" #import "NimbusPagingScrollView.h" #import <Foundation/Foundation.h> @class NIPhotoAlbumScrollView; /** * The photo album scroll data source. * * @ingroup NimbusPhotos * * This data source emphasizes speed and memory efficiency by requesting images only when * they're needed and encouraging immediate responses from the data source implementation. * * @see NIPhotoAlbumScrollView */ @protocol NIPhotoAlbumScrollViewDataSource <NIPagingScrollViewDataSource> @required #pragma mark Fetching Required Album Information /** @name [NIPhotoAlbumScrollViewDataSource] Fetching Required Album Information */ /** * Fetches the highest-quality image available for the photo at the given index. * * Your goal should be to make this implementation return as fast as possible. Avoid * hitting the disk or blocking on a network request. Aim to load images asynchronously. * * If you already have the highest-quality image in memory (like in an NIImageMemoryCache), * then you can simply return the image and set photoSize to be * NIPhotoScrollViewPhotoSizeOriginal. * * If the highest-quality image is not available when this method is called then you should * spin off an asynchronous operation to load the image and set isLoading to YES. * * If you have a thumbnail in memory but not the full-size image yet, then you should return * the thumbnail, set isLoading to YES, and set photoSize to NIPhotoScrollViewPhotoSizeThumbnail. * * Once the high-quality image finishes loading, call didLoadPhoto:atIndex:photoSize: with * the image. * * This method will be called to prefetch the next and previous photos in the scroll view. * The currently displayed photo will always be requested first. * * @attention The photo scroll view does not hold onto the UIImages for very long at all. * It is up to the controller to decide on an adequate caching policy to ensure * that images are kept in memory through the life of the photo album. * In your implementation of the data source you should prioritize thumbnails * being kept in memory over full-size images. When a memory warning is received, * the original photos should be relinquished from memory first. */ - (UIImage *)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView photoAtIndex: (NSInteger)photoIndex photoSize: (NIPhotoScrollViewPhotoSize *)photoSize isLoading: (BOOL *)isLoading originalPhotoDimensions: (CGSize *)originalPhotoDimensions; @optional #pragma mark Optimizing Data Retrieval /** @name [NIPhotoAlbumScrollViewDataSource] Optimizing Data Retrieval */ /** * Called when you should cancel any asynchronous loading requests for the given photo. * * When a photo is not immediately visible this method is called to allow the data * source to minimize the number of active asynchronous operations in place. * * This method is optional, though recommended because it focuses the device's processing * power on the most immediately accessible photos. */ - (void)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView stopLoadingPhotoAtIndex: (NSInteger)photoIndex; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoAlbumScrollViewDelegate.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import "NimbusPagingScrollView.h" @class NIPhotoAlbumScrollView; /** * The photo album scroll view delegate. * * @ingroup Photos-Protocols * @see NIPhotoAlbumScrollView */ @protocol NIPhotoAlbumScrollViewDelegate <NIPagingScrollViewDelegate> @optional #pragma mark Scrolling and Zooming /** @name [NIPhotoAlbumScrollViewDelegate] Scrolling and Zooming */ /** * The user double-tapped to zoom in or out. */ - (void)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView didZoomIn: (BOOL)didZoomIn; #pragma mark Data Availability /** @name [NIPhotoAlbumScrollViewDelegate] Data Availability */ /** * The next photo in the album has been loaded and is ready to be displayed. */ - (void)photoAlbumScrollViewDidLoadNextPhoto:(NIPhotoAlbumScrollView *)photoAlbumScrollView; /** * The previous photo in the album has been loaded and is ready to be displayed. */ - (void)photoAlbumScrollViewDidLoadPreviousPhoto:(NIPhotoAlbumScrollView *)photoAlbumScrollView; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrollView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPagingScrollViewPage.h" #import "NIPhotoScrollViewPhotoSize.h" #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @protocol NIPhotoScrollViewDelegate; @class NICenteringScrollView; /** * A single photo view that supports zooming and rotation. * * @ingroup NimbusPhotos */ @interface NIPhotoScrollView : UIView <UIScrollViewDelegate, NIPagingScrollViewPage> #pragma mark Configuring Functionality @property (nonatomic, assign, getter=isZoomingEnabled) BOOL zoomingIsEnabled; // default: yes @property (nonatomic, assign, getter=isZoomingAboveOriginalSizeEnabled) BOOL zoomingAboveOriginalSizeIsEnabled; // default: yes @property (nonatomic, assign, getter=isDoubleTapToZoomEnabled) BOOL doubleTapToZoomIsEnabled; // default: yes @property (nonatomic, assign) CGFloat maximumScale; // default: 0 (autocalculate) @property (nonatomic, weak) id<NIPhotoScrollViewDelegate> photoScrollViewDelegate; #pragma mark State - (UIImage *)image; - (NIPhotoScrollViewPhotoSize)photoSize; - (void)setImage:(UIImage *)image photoSize:(NIPhotoScrollViewPhotoSize)photoSize; @property (nonatomic, assign, getter = isLoading) BOOL loading; @property (nonatomic, assign) NSInteger pageIndex; @property (nonatomic, assign) CGSize photoDimensions; @property (nonatomic, readonly, strong) UITapGestureRecognizer* doubleTapGestureRecognizer; @end /** @name Configuring Functionality */ /** * Whether the photo is allowed to be zoomed. * * By default this is YES. * * @fn NIPhotoScrollView::zoomingIsEnabled */ /** * Whether small photos can be zoomed at least until they fit the screen. * * If this is disabled, images smaller than the view size can not be zoomed in beyond * their original dimensions. * * If this is enabled, images smaller than the view size can be zoomed in only until * they fit the view bounds. * * The default behavior in Photos.app allows small photos to be zoomed in. * * @attention This will allow photos to be zoomed in even if they don't have any more * pixels to show, causing the photo to blur. This can look ok for photographs, * but might not look ok for software design mockups. * * By default this is YES. * * @fn NIPhotoScrollView::zoomingAboveOriginalSizeIsEnabled */ /** * Whether double-tapping zooms in and out of the image. * * Available on iOS 3.2 and later. * * By default this is YES. * * @fn NIPhotoScrollView::doubleTapToZoomIsEnabled */ /** * The maximum scale of the image. * * By default this is 0, meaning the view will automatically determine the maximum scale. * Setting this to a non-zero value will override the automatically-calculated maximum scale. * * @fn NIPhotoScrollView::maximumScale */ /** * The photo scroll view delegate. * * @fn NIPhotoScrollView::photoScrollViewDelegate */ /** @name State */ /** * The currently-displayed photo. * * @fn NIPhotoScrollView::image */ /** * Set a new photo with a specific size. * * If image is nil then the photoSize will be overridden as NIPhotoScrollViewPhotoSizeUnknown. * * Resets the current zoom levels and zooms to fit the image. * * @fn NIPhotoScrollView::setImage:photoSize: */ /** * The index of this photo within a photo album. * * @fn NIPhotoScrollView::pageIndex */ /** * The current size of the photo. * * This is used to replace the photo only with successively higher-quality versions. * * @fn NIPhotoScrollView::photoSize */ /** * The largest dimensions of the photo. * * This is used to show the thumbnail at the final image size in case the final image size * is smaller than the album's frame. Without this value we have to assume that the thumbnail * will take up the full screen. If the final image doesn't take up the full screen, then * the photo view will appear to "snap" to the smaller full-size image when the final image * does load. * * CGSizeZero is used to signify an unknown final photo dimension. * * @fn NIPhotoScrollView::photoDimensions */ /** * The gesture recognizer for double-tapping zooms in and out of the image. * * This is used mainly for setting up dependencies between gesture recognizers. * * @fn NIPhotoScrollView::doubleTapGestureRecognizer */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrollView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPhotoScrollView.h" #import "NIPhotoScrollViewDelegate.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif /** * A UIScrollView that centers the zooming view's frame as the user zooms. * * We must update the zooming view's frame within the scroll view's layoutSubviews, * thus why we've subclassed UIScrollView. */ @interface NICenteringScrollView : UIScrollView @end @implementation NICenteringScrollView #pragma mark - UIView - (void)layoutSubviews { [super layoutSubviews]; // Center the image as it becomes smaller than the size of the screen. UIView* zoomingSubview = [self.delegate viewForZoomingInScrollView:self]; CGSize boundsSize = self.bounds.size; CGRect frameToCenter = zoomingSubview.frame; // Center horizontally. if (frameToCenter.size.width < boundsSize.width) { frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2); } else { frameToCenter.origin.x = 0; } // Center vertically. if (frameToCenter.size.height < boundsSize.height) { frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2); } else { frameToCenter.origin.y = 0; } zoomingSubview.frame = frameToCenter; } @end @interface NIPhotoScrollView () @property (nonatomic, assign) NIPhotoScrollViewPhotoSize photoSize; - (void)setMaxMinZoomScalesForCurrentBounds; @end @implementation NIPhotoScrollView { // The photo view to be zoomed. UIImageView* _imageView; // The scroll view. NICenteringScrollView* _scrollView; UIActivityIndicatorView* _loadingView; // Photo Information NIPhotoScrollViewPhotoSize _photoSize; CGSize _photoDimensions; // Configurable State BOOL _zoomingIsEnabled; BOOL _zoomingAboveOriginalSizeIsEnabled; UITapGestureRecognizer* _doubleTapGestureRecognizer; } @synthesize reuseIdentifier; - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { // Default configuration. self.zoomingIsEnabled = YES; self.zoomingAboveOriginalSizeIsEnabled = YES; self.doubleTapToZoomIsEnabled = YES; // Autorelease so that we don't have to worry about releasing the subviews in dealloc. _scrollView = [[NICenteringScrollView alloc] initWithFrame:self.bounds]; _scrollView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); _loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; [_loadingView sizeToFit]; _loadingView.frame = NIFrameOfCenteredViewWithinView(_loadingView, self); _loadingView.autoresizingMask = UIViewAutoresizingFlexibleMargins; // We implement viewForZoomingInScrollView: and return the image view for zooming. _scrollView.delegate = self; // Disable the scroll indicators. _scrollView.showsVerticalScrollIndicator = NO; _scrollView.showsHorizontalScrollIndicator = NO; // Photo viewers should feel sticky when you're panning around, not smooth and slippery // like a UITableView. _scrollView.decelerationRate = UIScrollViewDecelerationRateFast; // Ensure that empty areas of the scroll view are draggable. self.backgroundColor = [UIColor blackColor]; _scrollView.backgroundColor = self.backgroundColor; _imageView = [[UIImageView alloc] initWithFrame:CGRectZero]; [_scrollView addSubview:_imageView]; [self addSubview:_scrollView]; [self addSubview:_loadingView]; } return self; } - (void)setBackgroundColor:(UIColor *)backgroundColor { [super setBackgroundColor:backgroundColor]; _scrollView.backgroundColor = backgroundColor; } #pragma mark - UIScrollView - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return _imageView; } #pragma mark - Gesture Recognizers - (CGRect)rectAroundPoint:(CGPoint)point atZoomScale:(CGFloat)zoomScale { NIDASSERT(zoomScale > 0); // Define the shape of the zoom rect. CGSize boundsSize = self.bounds.size; // Modify the size according to the requested zoom level. // For example, if we're zooming in to 0.5 zoom, then this will increase the bounds size // by a factor of two. CGSize scaledBoundsSize = CGSizeMake(boundsSize.width / zoomScale, boundsSize.height / zoomScale); CGRect rect = CGRectMake(point.x - scaledBoundsSize.width / 2, point.y - scaledBoundsSize.height / 2, scaledBoundsSize.width, scaledBoundsSize.height); // When the image is zoomed out there is a bit of empty space around the image due // to the fact that it's centered on the screen. When we created the rect around the // point we need to take this "space" into account. // 1: get the frame of the image in this view's coordinates. CGRect imageScaledFrame = [self convertRect:_imageView.frame toView:self]; // 2: Offset the frame by the excess amount. This will ensure that the zoomed location // is always centered on the tap location. We only allow positive values because a // negative value implies that there isn't actually any offset. rect = CGRectOffset(rect, -MAX(0, imageScaledFrame.origin.x), -MAX(0, imageScaledFrame.origin.y)); return rect; } - (void)didDoubleTap:(UITapGestureRecognizer *)tapGesture { BOOL isCompletelyZoomedIn = (_scrollView.maximumZoomScale <= _scrollView.zoomScale + FLT_EPSILON); BOOL didZoomIn; if (isCompletelyZoomedIn) { // Zoom the photo back out. [_scrollView setZoomScale:_scrollView.minimumZoomScale animated:YES]; didZoomIn = NO; } else { // Zoom into the tap point. CGPoint tapCenter = [tapGesture locationInView:_imageView]; CGRect maxZoomRect = [self rectAroundPoint:tapCenter atZoomScale:_scrollView.maximumZoomScale]; [_scrollView zoomToRect:maxZoomRect animated:YES]; didZoomIn = YES; } if ([self.photoScrollViewDelegate respondsToSelector: @selector(photoScrollViewDidDoubleTapToZoom:didZoomIn:)]) { [self.photoScrollViewDelegate photoScrollViewDidDoubleTapToZoom:self didZoomIn:didZoomIn]; } } #pragma mark - NIPagingScrollViewPage - (void)prepareForReuse { _imageView.image = nil; self.photoSize = NIPhotoScrollViewPhotoSizeUnknown; _scrollView.zoomScale = 1; _scrollView.contentSize = self.bounds.size; } - (void)pageDidDisappear { _scrollView.zoomScale = _scrollView.minimumZoomScale; } #pragma mark - Public - (void)setImage:(UIImage *)image photoSize:(NIPhotoScrollViewPhotoSize)photoSize { _imageView.image = image; [_imageView sizeToFit]; if (nil == image) { self.photoSize = NIPhotoScrollViewPhotoSizeUnknown; } else { self.photoSize = photoSize; } // The min/max zoom values assume that the content size is the image size. The max zoom will // be a value that allows the image to be seen at a 1-to-1 pixel resolution, while the min // zoom will be small enough to fit the image on the screen perfectly. if (nil != image) { _scrollView.contentSize = image.size; } else { _scrollView.contentSize = self.bounds.size; } [self setMaxMinZoomScalesForCurrentBounds]; // Start off with the image fully-visible on the screen. _scrollView.zoomScale = _scrollView.minimumZoomScale; [self setNeedsLayout]; } - (void)setLoading:(BOOL)loading { _loading = loading; if (loading) { [_loadingView startAnimating]; } else { [_loadingView stopAnimating]; } } - (UIImage *)image { return _imageView.image; } - (void)setZoomingIsEnabled:(BOOL)enabled { _zoomingIsEnabled = enabled; if (nil != _imageView.image) { [self setMaxMinZoomScalesForCurrentBounds]; // Fit the image on screen. _scrollView.zoomScale = _scrollView.minimumZoomScale; // Disable zoom bouncing if zooming is disabled, otherwise the view will allow pinching. _scrollView.bouncesZoom = enabled; } else { // Reset to the defaults if there is no set image yet. _scrollView.zoomScale = 1; _scrollView.minimumZoomScale = 1; _scrollView.maximumZoomScale = 1; _scrollView.bouncesZoom = NO; } } - (void)setDoubleTapToZoomIsEnabled:(BOOL)enabled { if (enabled && nil == _doubleTapGestureRecognizer) { _doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didDoubleTap:)]; _doubleTapGestureRecognizer.numberOfTapsRequired = 2; [self addGestureRecognizer:_doubleTapGestureRecognizer]; } _doubleTapGestureRecognizer.enabled = enabled; } - (BOOL)isDoubleTapToZoomEnabled { return [_doubleTapGestureRecognizer isEnabled]; } - (CGFloat)scaleForSize:(CGSize)size boundsSize:(CGSize)boundsSize useMinimalScale:(BOOL)minimalScale { CGFloat xScale = boundsSize.width / size.width; // The scale needed to perfectly fit the image width-wise. CGFloat yScale = boundsSize.height / size.height; // The scale needed to perfectly fit the image height-wise. CGFloat minScale = minimalScale ? MIN(xScale, yScale) : MAX(xScale, yScale); // Use the minimum of these to allow the image to become fully visible, or the maximum to get fullscreen size return minScale; } /** * Calculate the min and max scale for the given dimensions and photo size. * * minScale will fit the photo to the bounds, unless it is too small in which case it will * show the image at a 1-to-1 resolution. * * maxScale will be whatever value shows the image at a 1-to-1 resolution, UNLESS * isZoomingAboveOriginalSizeEnabled is enabled, in which case maxScale will be calculated * such that the image completely fills the bounds. * * Exception: If the photo size is unknown (this is a loading image, for example) then * the minimum scale will be set without considering the screen scale. This allows the * loading image to draw with its own image scale if it's a high-res @2x image. */ - (void)minAndMaxScaleForDimensions: (CGSize)dimensions boundsSize: (CGSize)boundsSize photoSize: (NIPhotoScrollViewPhotoSize)photoSize minScale: (CGFloat *)pMinScale maxScale: (CGFloat *)pMaxScale { NIDASSERT(nil != pMinScale); NIDASSERT(nil != pMaxScale); if (nil == pMinScale || nil == pMaxScale) { return; } CGFloat minScale = [self scaleForSize: dimensions boundsSize: boundsSize useMinimalScale: YES]; // On high resolution screens we have double the pixel density, so we will be seeing // every pixel if we limit the maximum zoom scale to 0.5. // If the photo size is unknown, it's likely that we're showing the loading image and // don't want to shrink it down with the zoom because it should be a scaled image. CGFloat maxScale = ((NIPhotoScrollViewPhotoSizeUnknown == photoSize) ? 1 : (1.0f / NIScreenScale())); if (NIPhotoScrollViewPhotoSizeThumbnail != photoSize) { // Don't let minScale exceed maxScale. (If the image is smaller than the screen, we // don't want to force it to be zoomed.) minScale = MIN(minScale, maxScale); } // At this point if the image is small, then minScale and maxScale will be the same because // we don't want to allow the photo to be zoomed. // If zooming above the original size IS enabled, however, expand the max zoom to // whatever value would make the image fit the view perfectly. if ([self isZoomingAboveOriginalSizeEnabled]) { CGFloat idealMaxScale = [self scaleForSize: dimensions boundsSize: boundsSize useMinimalScale: NO]; maxScale = MAX(maxScale, idealMaxScale); } *pMinScale = minScale; *pMaxScale = maxScale; } - (void)setMaxMinZoomScalesForCurrentBounds { CGSize imageSize = _imageView.bounds.size; // Avoid crashing if the image has no dimensions. if (imageSize.width <= 0 || imageSize.height <= 0) { _scrollView.maximumZoomScale = 1; _scrollView.minimumZoomScale = 1; return; } // The following code is from Apple's ImageScrollView example application and has been used // here because it is well-documented and concise. CGSize boundsSize = _scrollView.bounds.size; CGFloat minScale = 0; CGFloat maxScale = 0; // Calculate the min/max scale for the image to be presented. [self minAndMaxScaleForDimensions: imageSize boundsSize: boundsSize photoSize: self.photoSize minScale: &minScale maxScale: &maxScale]; // When we show thumbnails for images that are too small for the bounds, we try to use // the known photo dimensions to scale the minimum scale to match what the final image // would be. This avoids any "snapping" effects from stretching the thumbnail too large. if ((NIPhotoScrollViewPhotoSizeThumbnail == self.photoSize) && !CGSizeEqualToSize(self.photoDimensions, CGSizeZero)) { CGFloat scaleToFitOriginal = 0; CGFloat originalMaxScale = 0; // Calculate the original-sized image's min/max scale. [self minAndMaxScaleForDimensions: self.photoDimensions boundsSize: boundsSize photoSize: NIPhotoScrollViewPhotoSizeOriginal minScale: &scaleToFitOriginal maxScale: &originalMaxScale]; if (scaleToFitOriginal + FLT_EPSILON >= (1.0 / NIScreenScale())) { // If the final image will be smaller than the view then we want to use that // scale as the "true" scale and adjust it relatively to the thumbnail's dimensions. // This ensures that the thumbnail will always be the same visual size as the original // image, giving us that sexy "crisping" effect when the thumbnail is loaded. CGFloat relativeSize = self.photoDimensions.width / imageSize.width; minScale = scaleToFitOriginal * relativeSize; } } // If zooming is disabled then we flatten the range for zooming to only allow the min zoom. if (self.isZoomingEnabled && NIPhotoScrollViewPhotoSizeOriginal == self.photoSize && self.maximumScale > 0) { _scrollView.maximumZoomScale = self.maximumScale; } else { _scrollView.maximumZoomScale = self.isZoomingEnabled ? maxScale : minScale; } _scrollView.minimumZoomScale = minScale; } #pragma mark Saving/Restoring Offset and Scale // Parts of the following code are from Apple's ImageScrollView example application and // have been used here because they are well-documented and concise. // Fetch the visual center point of this view in the image view's coordinate space. - (CGPoint)pointToCenterAfterRotation { CGRect bounds = _scrollView.bounds; CGPoint boundsCenter = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)); return [self convertPoint:boundsCenter toView:_imageView]; } - (CGFloat)scaleToRestoreAfterRotation { CGFloat contentScale = _scrollView.zoomScale; // If we're at the minimum zoom scale, preserve that by returning 0, which // will be converted to the minimum allowable scale when the scale is restored. if (contentScale <= _scrollView.minimumZoomScale + FLT_EPSILON) { contentScale = 0; } return contentScale; } - (CGPoint)maximumContentOffset { CGSize contentSize = _scrollView.contentSize; CGSize boundsSize = _scrollView.bounds.size; return CGPointMake(contentSize.width - boundsSize.width, contentSize.height - boundsSize.height); } - (CGPoint)minimumContentOffset { return CGPointZero; } - (void)restoreCenterPoint:(CGPoint)oldCenter scale:(CGFloat)oldScale { // Step 1: restore zoom scale, making sure it is within the allowable range. _scrollView.zoomScale = NIBoundf(oldScale, _scrollView.minimumZoomScale, _scrollView.maximumZoomScale); // Step 2: restore center point, making sure it is within the allowable range. // 2a: convert our desired center point back to the scroll view's coordinate space from the // image's coordinate space. CGPoint boundsCenter = [self convertPoint:oldCenter fromView:_imageView]; // 2b: calculate the content offset that would yield that center point CGPoint offset = CGPointMake(boundsCenter.x - _scrollView.bounds.size.width / 2.0f, boundsCenter.y - _scrollView.bounds.size.height / 2.0f); // 2c: restore offset, adjusted to be within the allowable range CGPoint maxOffset = [self maximumContentOffset]; CGPoint minOffset = [self minimumContentOffset]; offset.x = NIBoundf(offset.x, minOffset.x, maxOffset.x); offset.y = NIBoundf(offset.y, minOffset.y, maxOffset.y); _scrollView.contentOffset = offset; } #pragma mark Saving/Restoring Offset and Scale - (void)setFrameAndMaintainState:(CGRect)frame { CGPoint restorePoint = [self pointToCenterAfterRotation]; CGFloat restoreScale = [self scaleToRestoreAfterRotation]; self.frame = frame; [self setMaxMinZoomScalesForCurrentBounds]; [self restoreCenterPoint:restorePoint scale:restoreScale]; [_scrollView setNeedsLayout]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrollViewDelegate.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> @class NIPhotoScrollView; /** * The photo scroll view delegate. * * @ingroup NimbusPhotos */ @protocol NIPhotoScrollViewDelegate <NSObject> @optional #pragma mark Zooming /** @name [NIPhotoScrollViewDelegate] Zooming */ /** * The user has double-tapped the photo to zoom either in or out. * * @param photoScrollView The photo scroll view that was tapped. * @param didZoomIn YES if the photo was zoomed in. NO if the photo was zoomed out. */ - (void)photoScrollViewDidDoubleTapToZoom: (NIPhotoScrollView *)photoScrollView didZoomIn: (BOOL)didZoomIn; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrollViewPhotoSize.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> /** * Contextual information about the size of the photo. */ typedef enum { // Unknown photo size. NIPhotoScrollViewPhotoSizeUnknown, // A smaller version of the image. NIPhotoScrollViewPhotoSizeThumbnail, // The full-size image. NIPhotoScrollViewPhotoSizeOriginal, } NIPhotoScrollViewPhotoSize;
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrubberView.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for weak */ @protocol NIPhotoScrubberViewDataSource; @protocol NIPhotoScrubberViewDelegate; /** * A control built for quickly skimming through a collection of images. * * @ingroup NimbusPhotos * * The user interacts with the scrubber by "scrubbing" their finger along the control, * or more simply, touching the control and moving their finger along a single axis. * Scrubbers can be seen in the Photos.app on the iPad. * * The thumbnails displayed in a scrubber will be a subset of the overall set of photos. * The wider the scrubber, the more thumbnails will be shown. The displayed thumbnails will * be chosen at constant intervals in the album, with a larger "selected" thumbnail image * that will show whatever image is currently selected. This larger thumbnail will be * positioned relatively within the scrubber to show the user what the current selection * is in a physically intuitive way. * * This view is a completely independent view from the photo scroll view so you can choose * to use this in your already built photo viewer. * * @image html scrubber1.png "Screenshot of NIPhotoScrubberView on the iPad." * * @see NIPhotoScrubberViewDataSource * @see NIPhotoScrubberViewDelegate */ @interface NIPhotoScrubberView : UIView #pragma mark Data Source /** @name Data Source */ /** * The data source for this scrubber view. */ @property (nonatomic, weak) id<NIPhotoScrubberViewDataSource> dataSource; /** * Forces the scrubber view to reload all of its data. * * This must be called at least once after dataSource has been set in order for the view * to gather any presentable information. * * This method is expensive. It will reset the state of the view and remove all existing * thumbnails before requesting the new information from the data source. */ - (void)reloadData; /** * Notify the scrubber view that a thumbnail has been loaded at a given index. * * This method is cheap, so do not be afraid to call it whenever a thumbnail loads. * It will only modify visible thumbnails. */ - (void)didLoadThumbnail: (UIImage *)image atIndex: (NSInteger)photoIndex; #pragma mark Delegate /** @name Delegate */ /** * The delegate for this scrubber view. */ @property (nonatomic, weak) id<NIPhotoScrubberViewDelegate> delegate; #pragma mark Accessing Selection /** @name Accessing Selection */ /** * The selected photo index. */ @property (nonatomic, assign) NSInteger selectedPhotoIndex; /** * Set the selected photo with animation. */ - (void)setSelectedPhotoIndex:(NSInteger)photoIndex animated:(BOOL)animated; @end /** * The data source for the photo scrubber. * * @ingroup NimbusPhotos * * <h2>Performance Considerations</h2> * * A scrubber view's purpose is for instantly flipping through an album of photos. As such, * it's crucial that your implementation of the data source performs blazingly fast. When * the scrubber requests a thumbnail from you you should *not* be hitting the disk or blocking * on a network call. If you don't have the thumbnail available at that exact moment, fire * off an asynchronous load request (using NIReadFileFromDiskOperation or NIHTTPRequest) * and return nil. Once the thumbnail is loaded, call didLoadThumbnail:atIndex: to notify * the scrubber that it can display the thumbnail now. * * It is not recommended to use high-res images for your scrubber thumbnails. This is because * the scrubber will keep a large set of images in memory and if you're giving it * high-resolution images then you'll find that your app quickly burns through memory. * If you don't have access to thumbnails from whatever API you're using then you should consider * not using a scrubber. * * @see NIPhotoScrubberView */ @protocol NIPhotoScrubberViewDataSource <NSObject> @required #pragma mark Fetching Required Information /** @name Fetching Required Information */ /** * Fetches the total number of photos in the scroll view. * * The value returned in this method will be cached by the scroll view until reloadData * is called again. */ - (NSInteger)numberOfPhotosInScrubberView:(NIPhotoScrubberView *)photoScrubberView; /** * Fetch the thumbnail image for the given photo index. * * Please read and understand the performance considerations for this data source. */ - (UIImage *)photoScrubberView: (NIPhotoScrubberView *)photoScrubberView thumbnailAtIndex: (NSInteger)thumbnailIndex; @end /** * The delegate for the photo scrubber. * * @ingroup NimbusPhotos * * Sends notifications of state changes. * * @see NIPhotoScrubberView */ @protocol NIPhotoScrubberViewDelegate <NSObject> @optional #pragma mark Selection Changes /** @name Selection Changes */ /** * The photo scrubber changed its selection. * * Use photoScrubberView.selectedPhotoIndex to access the current selection. */ - (void)photoScrubberViewDidChangeSelection:(NIPhotoScrubberView *)photoScrubberView; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIPhotoScrubberView.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIPhotoScrubberView.h" #import "NimbusCore.h" #import <QuartzCore/QuartzCore.h> #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif static const NSInteger NIPhotoScrubberViewUnknownTag = -1; @interface NIPhotoScrubberView() /** * @internal * * A method to encapsulate initilization logic that can be shared by different init methods. */ - (void)initializeScrubber; /** * @internal * * A lightweight method for updating all of the visible thumbnails in the scrubber. * * This method will force the scrubber to lay itself out, calculate how many thumbnails might * be visible, and then lay out the thumbnails and fetch any thumbnail images it can find. * * This method should never take much time to run, so it can safely be used in layoutSubviews. */ - (void)updateVisiblePhotos; /** * @internal * * Returns a new, autoreleased image view in the style of this photo scrubber. * * This implementation returns an image with a 1px solid white border and a black background. */ - (UIImageView *)photoView; @end @implementation NIPhotoScrubberView { NSMutableArray* _visiblePhotoViews; NSMutableSet* _recycledPhotoViews; UIView* _containerView; UIImageView* _selectionView; // State NSInteger _selectedPhotoIndex; // Cached data source values NSInteger _numberOfPhotos; // Cached display values NSInteger _numberOfVisiblePhotos; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self initializeScrubber]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if ((self = [super initWithCoder:aDecoder])) { [self initializeScrubber]; } return self; } - (void)initializeScrubber { // Only one finger should be allowed to interact with the scrubber at a time. self.multipleTouchEnabled = NO; _containerView = [[UIView alloc] init]; _containerView.layer.borderColor = [UIColor colorWithWhite:1 alpha:0.1f].CGColor; _containerView.layer.borderWidth = 1; _containerView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.3f]; _containerView.userInteractionEnabled = NO; [self addSubview:_containerView]; _selectionView = [self photoView]; [self addSubview:_selectionView]; _selectedPhotoIndex = -1; } #pragma mark - View Creation - (UIImageView *)photoView { UIImageView* imageView = [[UIImageView alloc] init]; imageView.layer.borderColor = [UIColor whiteColor].CGColor; imageView.layer.borderWidth = 1; imageView.backgroundColor = [UIColor blackColor]; imageView.clipsToBounds = YES; imageView.userInteractionEnabled = NO; imageView.contentMode = UIViewContentModeScaleAspectFill; imageView.tag = NIPhotoScrubberViewUnknownTag; return imageView; } #pragma mark - Layout - (CGSize)photoSize { CGSize boundsSize = self.bounds.size; // These numbers are roughly estimated from the Photos.app's scrubber. CGFloat photoWidth = floorf(boundsSize.height / 2.4f); CGFloat photoHeight = floorf(photoWidth * 0.75f); return CGSizeMake(photoWidth, photoHeight); } - (CGSize)selectionSize { CGSize boundsSize = self.bounds.size; // These numbers are roughly estimated from the Photos.app's scrubber. CGFloat selectionWidth = floorf(boundsSize.height / 1.2f); CGFloat selectionHeight = floorf(selectionWidth * 0.75f); return CGSizeMake(selectionWidth, selectionHeight); } // The amount of space on either side of the scrubber's left and right edges. - (CGFloat)horizontalMargins { CGSize photoSize = [self photoSize]; return floorf(photoSize.width / 2); } - (CGFloat)spaceBetweenPhotos { return 1; } // The maximum number of pixels that the scrubber can utilize. The scrubber layer's border // is contained within this width and must be considered when laying out the thumbnails. - (CGFloat)maxContentWidth { CGSize boundsSize = self.bounds.size; CGFloat horizontalMargins = [self horizontalMargins]; CGFloat maxContentWidth = (boundsSize.width - horizontalMargins * 2); return maxContentWidth; } - (NSInteger)numberOfVisiblePhotos { CGSize photoSize = [self photoSize]; CGFloat spaceBetweenPhotos = [self spaceBetweenPhotos]; // Here's where we take into account the container layer's border because we don't want to // display thumbnails on top of the border. CGFloat maxContentWidth = ([self maxContentWidth] - _containerView.layer.borderWidth * 2); NSInteger numberOfPhotosThatFit = (NSInteger)floor((maxContentWidth + spaceBetweenPhotos) / (photoSize.width + spaceBetweenPhotos)); return MIN(_numberOfPhotos, numberOfPhotosThatFit); } - (CGRect)frameForSelectionAtIndex:(NSInteger)photoIndex { CGSize photoSize = [self photoSize]; CGSize selectionSize = [self selectionSize]; CGFloat containerWidth = _containerView.bounds.size.width; // TODO (jverkoey July 21, 2011): I need to figure out why this is necessary. // Basically, when there are a lot of photos it seems like the selection frame // slowly gets offset from the thumbnail frame it's supposed to be representing until by the end // it's off the right edge by a noticeable amount. Trimming off some fat from the right // edge seems to fix this. if (_numberOfVisiblePhotos < _numberOfPhotos) { containerWidth -= photoSize.width / 2; } // Calculate the offset into the container view based on index/numberOfPhotos. CGFloat relativeOffset = floorf((((CGFloat)photoIndex * containerWidth) / (CGFloat)MAX(1, _numberOfPhotos))); return CGRectMake(floorf(_containerView.frame.origin.x + relativeOffset + photoSize.width / 2 - selectionSize.width / 2), floorf(_containerView.center.y - selectionSize.height / 2), selectionSize.width, selectionSize.height); } - (CGRect)frameForThumbAtIndex:(NSInteger)thumbIndex { CGSize photoSize = [self photoSize]; CGFloat spaceBetweenPhotos = [self spaceBetweenPhotos]; return CGRectMake(_containerView.layer.borderWidth + (photoSize.width + spaceBetweenPhotos) * thumbIndex, _containerView.layer.borderWidth, photoSize.width, photoSize.height); } - (void)layoutSubviews { [super layoutSubviews]; CGSize boundsSize = self.bounds.size; CGSize photoSize = [self photoSize]; CGFloat spaceBetweenPhotos = [self spaceBetweenPhotos]; CGFloat maxContentWidth = [self maxContentWidth]; // Update the total number of visible photos. _numberOfVisiblePhotos = [self numberOfVisiblePhotos]; // Hide views if there isn't any interesting information to show. _containerView.hidden = (0 == _numberOfVisiblePhotos); _selectionView.hidden = (_selectedPhotoIndex < 0 || _containerView.hidden); // Calculate the container width using the number of visible photos. CGFloat containerWidth = ((_numberOfVisiblePhotos * photoSize.width) + (MAX(0, _numberOfVisiblePhotos - 1) * spaceBetweenPhotos) + _containerView.layer.borderWidth * 2); // Then we center the container in the content area. CGFloat containerMargins = MAX(0, floorf((maxContentWidth - containerWidth) / 2)); CGFloat horizontalMargins = [self horizontalMargins]; CGFloat containerHeight = photoSize.height + _containerView.layer.borderWidth * 2; CGFloat containerLeftMargin = horizontalMargins + containerMargins; CGFloat containerTopMargin = floorf((boundsSize.height - containerHeight) / 2); _containerView.frame = CGRectMake(containerLeftMargin, containerTopMargin, containerWidth, containerHeight); // Don't bother updating the selected photo index if there isn't a selection; the // selection view will be hidden anyway. if (_selectedPhotoIndex >= 0) { _selectionView.frame = [self frameForSelectionAtIndex:_selectedPhotoIndex]; } // Update the frames for all of the thumbnails. [self updateVisiblePhotos]; } // Transforms an index into the number of visible photos into an index into the total // number of photos. - (NSInteger)photoIndexAtScrubberIndex:(NSInteger)scrubberIndex { return (NSInteger)(ceilf((CGFloat)(scrubberIndex * _numberOfPhotos) / (CGFloat)_numberOfVisiblePhotos) + 0.5f); } - (void)updateVisiblePhotos { if (nil == self.dataSource) { return; } // This will update the number of visible photos if the layout did indeed change. [self layoutIfNeeded]; // Recycle any views that we no longer need. while ([_visiblePhotoViews count] > (NSUInteger)_numberOfVisiblePhotos) { UIView* photoView = [_visiblePhotoViews lastObject]; [photoView removeFromSuperview]; [_recycledPhotoViews addObject:photoView]; [_visiblePhotoViews removeLastObject]; } // Lay out the visible photos. for (NSUInteger ix = 0; ix < (NSUInteger)_numberOfVisiblePhotos; ++ix) { UIImageView* photoView = nil; // We must first get the photo view at this index. // If there aren't enough visible photo views then try to recycle another view. if (ix >= [_visiblePhotoViews count]) { photoView = [_recycledPhotoViews anyObject]; if (nil == photoView) { // Couldn't recycle the view, so create a new one. photoView = [self photoView]; } else { [_recycledPhotoViews removeObject:photoView]; } [_containerView addSubview:photoView]; [_visiblePhotoViews addObject:photoView]; } else { photoView = [_visiblePhotoViews objectAtIndex:ix]; } NSInteger photoIndex = [self photoIndexAtScrubberIndex:ix]; // Only request the thumbnail if this thumbnail's photo index has changed. Otherwise // we assume that this photo either already has the thumbnail or it's still loading. if (photoView.tag != photoIndex) { photoView.tag = photoIndex; UIImage* image = [self.dataSource photoScrubberView:self thumbnailAtIndex:photoIndex]; photoView.image = image; if (_selectedPhotoIndex == photoIndex) { _selectionView.image = image; } } photoView.frame = [self frameForThumbAtIndex:ix]; } } #pragma mark - Changing Selection - (NSInteger)photoIndexAtPoint:(CGPoint)point { NSInteger photoIndex; if (point.x <= 0) { // Beyond the left edge photoIndex = 0; } else if (point.x >= _containerView.bounds.size.width) { // Beyond the right edge photoIndex = (_numberOfPhotos - 1); } else { // Somewhere in between photoIndex = (NSInteger)(floorf((point.x / _containerView.bounds.size.width) * _numberOfPhotos) + 0.5f); } return photoIndex; } - (void)updateSelectionWithPoint:(CGPoint)point { NSInteger photoIndex = [self photoIndexAtPoint:point]; if (photoIndex != _selectedPhotoIndex) { [self setSelectedPhotoIndex:photoIndex]; if ([self.delegate respondsToSelector:@selector(photoScrubberViewDidChangeSelection:)]) { [self.delegate photoScrubberViewDidChangeSelection:self]; } } } #pragma mark - UIResponder - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch* touch = [touches anyObject]; CGPoint touchPoint = [touch locationInView:_containerView]; [self updateSelectionWithPoint:touchPoint]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; UITouch* touch = [touches anyObject]; CGPoint touchPoint = [touch locationInView:_containerView]; [self updateSelectionWithPoint:touchPoint]; } #pragma mark - Public - (void)didLoadThumbnail: (UIImage *)image atIndex: (NSInteger)photoIndex { for (UIImageView* thumbView in _visiblePhotoViews) { if (thumbView.tag == photoIndex) { thumbView.image = image; break; } } // Update the selected thumbnail if it's the one that just received a photo. if (_selectedPhotoIndex == photoIndex) { _selectionView.image = image; } } - (void)reloadData { NIDASSERT(nil != _dataSource); // Remove any visible photos from the view before we release the sets. for (UIView* photoView in _visiblePhotoViews) { [photoView removeFromSuperview]; } // If there is no data source then we can't do anything particularly interesting. if (nil == _dataSource) { return; } _visiblePhotoViews = [[NSMutableArray alloc] init]; _recycledPhotoViews = [[NSMutableSet alloc] init]; // Cache the number of photos. _numberOfPhotos = [_dataSource numberOfPhotosInScrubberView:self]; [self setNeedsLayout]; // This will call layoutIfNeeded and layoutSubviews will then be called because we // set the needsLayout flag. [self updateVisiblePhotos]; } - (void)setSelectedPhotoIndex:(NSInteger)photoIndex animated:(BOOL)animated { if (_selectedPhotoIndex != photoIndex) { // Don't animate the selection if it was previously invalid. animated = animated && (_selectedPhotoIndex >= 0); _selectedPhotoIndex = photoIndex; if (animated) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.2]; [UIView setAnimationCurve:UIViewAnimationCurveEaseOut]; [UIView setAnimationBeginsFromCurrentState:YES]; } _selectionView.frame = [self frameForSelectionAtIndex:_selectedPhotoIndex]; if (animated) { [UIView commitAnimations]; } _selectionView.image = [self.dataSource photoScrubberView: self thumbnailAtIndex: _selectedPhotoIndex]; } } - (void)setSelectedPhotoIndex:(NSInteger)photoIndex { [self setSelectedPhotoIndex:photoIndex animated:NO]; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIToolbarPhotoViewController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPhotoAlbumScrollView.h" #import "NIPhotoScrubberView.h" @class NIPhotoAlbumScrollView; /** * A simple photo album view controller implementation with a toolbar. * * @ingroup NimbusPhotos * * This controller does not implement the photo album data source, it simply implements * some of the most common UI elements that are associated with a photo viewer. * * For an example of implementing the data source, see the photos examples in the * examples directory. * * <h2>Implementing Delegate Methods</h2> * * This view controller already implements NIPhotoAlbumScrollViewDelegate. If you want to * implement methods of this delegate you should take care to call the super implementation * if necessary. The following methods have implementations in this class: * * - photoAlbumScrollViewDidScroll: * - photoAlbumScrollView:didZoomIn: * - photoAlbumScrollViewDidChangePages: * * * <h2>Recommended Configurations</h2> * * <h3>Default: Zooming enabled with translucent toolbar</h3> * * The default settings are good for showing a photo album that takes up the entire screen. * The photos will be visible beneath the toolbar because it is translucent. The chrome will * be hidden whenever the user starts interacting with the photos. * * @code * toolbarIsTranslucent = YES; * hidesChromeWhenScrolling = YES; * chromeCanBeHidden = YES; * @endcode * * <h3>Zooming disabled with opaque toolbar</h3> * * The following settings are good for viewing photo albums when you want to keep the chrome * visible at all times without zooming enabled. * * @code * toolbarIsTranslucent = NO; * chromeCanBeHidden = NO; * photoAlbumView.zoomingIsEnabled = NO; * @endcode */ @interface NIToolbarPhotoViewController : UIViewController <NIPhotoAlbumScrollViewDelegate, NIPhotoScrubberViewDelegate> #pragma mark Configuring Functionality @property (nonatomic, assign, getter=isToolbarTranslucent) BOOL toolbarIsTranslucent; // default: yes @property (nonatomic, assign) BOOL hidesChromeWhenScrolling; // default: yes @property (nonatomic, assign) BOOL chromeCanBeHidden; // default: yes @property (nonatomic, assign) BOOL animateMovingToNextAndPreviousPhotos; // default: no @property (nonatomic, assign, getter=isScrubberEnabled) BOOL scrubberIsEnabled; // default: ipad yes - iphone no #pragma mark Views @property (nonatomic, readonly, strong) UIToolbar* toolbar; @property (nonatomic, readonly, strong) NIPhotoAlbumScrollView* photoAlbumView; @property (nonatomic, readonly, strong) NIPhotoScrubberView* photoScrubberView; - (void)refreshChromeState; #pragma mark Toolbar Buttons @property (nonatomic, readonly, strong) UIBarButtonItem* nextButton; @property (nonatomic, readonly, strong) UIBarButtonItem* previousButton; #pragma mark Subclassing - (void)setChromeVisibility:(BOOL)isVisible animated:(BOOL)animated; - (void)setChromeTitle; @end /** @name Configuring Functionality */ /** * Whether the toolbar is translucent and shows photos beneath it or not. * * If this is enabled, the toolbar will be translucent and the photo view will * take up the entire view controller's bounds. * * If this is disabled, the photo will only occupy the remaining space above the * toolbar. The toolbar will also not be hidden when the chrome is dismissed. This is by design * because dismissing the toolbar when photos can't be displayed beneath it would leave * an empty space below the album. * * By default this is YES. * * @fn NIToolbarPhotoViewController::toolbarIsTranslucent */ /** * Whether or not to hide the chrome when the user begins interacting with the photo. * * If this is enabled, then the chrome will be hidden when the user starts swiping from * one photo to another. * * The chrome is the toolbar and the system status bar. * * By default this is YES. * * @attention This will be set to NO if toolbarCanBeHidden is set to NO. * * @fn NIToolbarPhotoViewController::hidesChromeWhenScrolling */ /** * Whether or not to allow hiding the chrome. * * If this is enabled then the user will be able to single-tap to dismiss or show the * toolbar. * * The chrome is the toolbar and the system status bar. * * If this is disabled then the chrome will always be visible. * * By default this is YES. * * @attention Setting this to NO will also disable hidesToolbarWhenScrolling. * * @fn NIToolbarPhotoViewController::chromeCanBeHidden */ /** * Whether to animate moving to a next or previous photo when the user taps the button. * * By default this is NO. * * @fn NIToolbarPhotoViewController::animateMovingToNextAndPreviousPhotos */ /** * Whether to show a scrubber in the toolbar instead of next/previous buttons. * * By default this is YES on the iPad and NO on the iPhone. * * @fn NIToolbarPhotoViewController::scrubberIsEnabled */ /** @name Views */ /** * The toolbar view. * * @fn NIToolbarPhotoViewController::toolbar */ /** * The photo album view. * * @fn NIToolbarPhotoViewController::photoAlbumView */ /** * The photo scrubber view. * * @fn NIToolbarPhotoViewController::photoScrubberView */ /** @name Toolbar Buttons */ /** * The 'next' button. * * @fn NIToolbarPhotoViewController::nextButton */ /** * The 'previous' button. * * @fn NIToolbarPhotoViewController::previousButton */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NIToolbarPhotoViewController.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIToolbarPhotoViewController.h" #import "NIPhotoAlbumScrollView.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @implementation NIToolbarPhotoViewController { // Views UIToolbar* _toolbar; NIPhotoAlbumScrollView* _photoAlbumView; // Scrubber View NIPhotoScrubberView* _photoScrubberView; // Toolbar Buttons UIBarButtonItem* _nextButton; UIBarButtonItem* _previousButton; // Gestures UITapGestureRecognizer* _tapGesture; // State BOOL _isAnimatingChrome; BOOL _isChromeHidden; BOOL _prefersStatusBarHidden; // Configuration BOOL _toolbarIsTranslucent; BOOL _hidesChromeWhenScrolling; BOOL _chromeCanBeHidden; BOOL _animateMovingToNextAndPreviousPhotos; BOOL _scrubberIsEnabled; } - (void)shutdown_NIToolbarPhotoViewController { _toolbar = nil; _photoAlbumView = nil; _nextButton = nil; _previousButton = nil; _photoScrubberView = nil; _tapGesture = nil; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Default Configuration Settings self.toolbarIsTranslucent = YES; self.hidesChromeWhenScrolling = YES; self.chromeCanBeHidden = YES; self.animateMovingToNextAndPreviousPhotos = NO; if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) { self.automaticallyAdjustsScrollViewInsets = NO; } // The scrubber is better use of the extra real estate on the iPad. // If you ask me, though, the scrubber works pretty well on the iPhone too. It's up // to you if you want to use it in your own implementations. self.scrubberIsEnabled = NIIsPad(); // Allow the photos to display beneath the status bar. self.wantsFullScreenLayout = YES; } return self; } - (void)addTapGestureToView { if ([self isViewLoaded]) { if (nil == _tapGesture) { _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap)]; [self.photoAlbumView addGestureRecognizer:_tapGesture]; } } _tapGesture.enabled = YES; } - (void)updateToolbarItems { UIBarItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil]; if ([self isScrubberEnabled]) { _nextButton = nil; _previousButton = nil; if (nil == _photoScrubberView) { CGRect scrubberFrame = CGRectMake(0, 0, self.toolbar.bounds.size.width, self.toolbar.bounds.size.height); _photoScrubberView = [[NIPhotoScrubberView alloc] initWithFrame:scrubberFrame]; _photoScrubberView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); _photoScrubberView.delegate = self; } UIBarButtonItem* scrubberItem = [[UIBarButtonItem alloc] initWithCustomView:self.photoScrubberView]; self.toolbar.items = [NSArray arrayWithObjects: flexibleSpace, scrubberItem, flexibleSpace, nil]; [_photoScrubberView setSelectedPhotoIndex:self.photoAlbumView.centerPageIndex]; } else { _photoScrubberView = nil; if (nil == _nextButton) { UIImage* nextIcon = [UIImage imageWithContentsOfFile: NIPathForBundleResource(nil, @"NimbusPhotos.bundle/gfx/next.png")]; // We weren't able to find the next or previous icons in your application's resources. // Ensure that you've dragged the NimbusPhotos.bundle from src/photos/resources into your // application with the "Create Folder References" option selected. You can verify that // you've done this correctly by expanding the NimbusPhotos.bundle file in your project // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being // copied in the Copy Bundle Resources phase. NIDASSERT(nil != nextIcon); _nextButton = [[UIBarButtonItem alloc] initWithImage: nextIcon style: UIBarButtonItemStylePlain target: self action: @selector(didTapNextButton)]; } if (nil == _previousButton) { UIImage* previousIcon = [UIImage imageWithContentsOfFile: NIPathForBundleResource(nil, @"NimbusPhotos.bundle/gfx/previous.png")]; // We weren't able to find the next or previous icons in your application's resources. // Ensure that you've dragged the NimbusPhotos.bundle from src/photos/resources into your // application with the "Create Folder References" option selected. You can verify that // you've done this correctly by expanding the NimbusPhotos.bundle file in your project // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being // copied in the Copy Bundle Resources phase. NIDASSERT(nil != previousIcon); _previousButton = [[UIBarButtonItem alloc] initWithImage: previousIcon style: UIBarButtonItemStylePlain target: self action: @selector(didTapPreviousButton)]; } self.toolbar.items = [NSArray arrayWithObjects: flexibleSpace, self.previousButton, flexibleSpace, self.nextButton, flexibleSpace, nil]; } } - (void)loadView { [super loadView]; self.view.backgroundColor = [UIColor blackColor]; CGRect bounds = self.view.bounds; // Toolbar Setup CGFloat toolbarHeight = NIToolbarHeightForOrientation(NIInterfaceOrientation()); CGRect toolbarFrame = CGRectMake(0, bounds.size.height - toolbarHeight, bounds.size.width, toolbarHeight); _toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame]; _toolbar.barStyle = UIBarStyleBlack; _toolbar.translucent = self.toolbarIsTranslucent; _toolbar.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin); [self updateToolbarItems]; // Photo Album View Setup CGRect photoAlbumFrame = bounds; if (!self.toolbarIsTranslucent) { photoAlbumFrame = NIRectContract(bounds, 0, toolbarHeight); } _photoAlbumView = [[NIPhotoAlbumScrollView alloc] initWithFrame:photoAlbumFrame]; _photoAlbumView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); _photoAlbumView.delegate = self; [self.view addSubview:_photoAlbumView]; [self.view addSubview:_toolbar]; if (self.hidesChromeWhenScrolling || self.chromeCanBeHidden) { [self addTapGestureToView]; } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[UIApplication sharedApplication] setStatusBarStyle: (NIIsPad() ? UIStatusBarStyleBlackOpaque : UIStatusBarStyleBlackTranslucent) animated: animated]; UINavigationBar* navBar = self.navigationController.navigationBar; navBar.barStyle = UIBarStyleBlack; navBar.translucent = self.toolbarIsTranslucent; _previousButton.enabled = [self.photoAlbumView hasPrevious]; _nextButton.enabled = [self.photoAlbumView hasNext]; } #if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_6_0 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return NIIsSupportedOrientation(toInterfaceOrientation); } #endif - (void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration { [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; [self.photoAlbumView willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; } - (void)willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation duration: (NSTimeInterval)duration { [self.photoAlbumView willAnimateRotationToInterfaceOrientation: toInterfaceOrientation duration: duration]; [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; CGRect toolbarFrame = self.toolbar.frame; toolbarFrame.size.height = NIToolbarHeightForOrientation(toInterfaceOrientation); toolbarFrame.origin.y = self.view.bounds.size.height - toolbarFrame.size.height; self.toolbar.frame = toolbarFrame; if (!self.toolbarIsTranslucent) { CGRect photoAlbumFrame = self.photoAlbumView.frame; photoAlbumFrame.size.height = self.view.bounds.size.height - toolbarFrame.size.height; self.photoAlbumView.frame = photoAlbumFrame; } } - (UIView *)rotatingFooterView { return self.toolbar.hidden ? nil : self.toolbar; } - (void)didHideChrome { _isAnimatingChrome = NO; if (self.toolbarIsTranslucent) { self.toolbar.hidden = YES; } [self.navigationController setNavigationBarHidden:YES animated:NO]; _isChromeHidden = YES; } - (void)didShowChrome { _isAnimatingChrome = NO; _isChromeHidden = NO; } - (UIStatusBarAnimation)preferredStatusBarUpdateAnimation { return UIStatusBarAnimationSlide; } - (BOOL)prefersStatusBarHidden { return _prefersStatusBarHidden; } - (void)setChromeVisibility:(BOOL)isVisible animated:(BOOL)animated { if (_isAnimatingChrome || (!isVisible && _isChromeHidden) || (isVisible && !_isChromeHidden) || !self.chromeCanBeHidden) { // Nothing to do here. return; } CGRect toolbarFrame = self.toolbar.frame; CGRect bounds = self.view.bounds; if (self.toolbarIsTranslucent) { // Reset the toolbar's initial position. if (!isVisible) { toolbarFrame.origin.y = bounds.size.height - toolbarFrame.size.height; } else { // Ensure that the toolbar is visible through the animation. self.toolbar.hidden = NO; toolbarFrame.origin.y = bounds.size.height; } self.toolbar.frame = toolbarFrame; } // Show/hide the system chrome. BOOL isStatusBarAppearanceSupported = [self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]; if (!isStatusBarAppearanceSupported) { [[UIApplication sharedApplication] setStatusBarHidden:!isVisible withAnimation:(animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone)]; } if (self.toolbarIsTranslucent) { // Place the toolbar at its final location. if (isVisible) { // Slide up. toolbarFrame.origin.y = bounds.size.height - toolbarFrame.size.height; } else { // Slide down. toolbarFrame.origin.y = bounds.size.height; } } // If there is a navigation bar, place it at its final location. CGRect navigationBarFrame = self.navigationController.navigationBar.frame; if (animated) { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:(isVisible ? @selector(didShowChrome) : @selector(didHideChrome))]; // Ensure that the animation matches the status bar's. [UIView setAnimationDuration:NIStatusBarAnimationDuration()]; [UIView setAnimationCurve:NIStatusBarAnimationCurve()]; } if (isStatusBarAppearanceSupported) { _prefersStatusBarHidden = !isVisible; [self setNeedsStatusBarAppearanceUpdate]; } if (nil != self.navigationController.navigationBar) { if (isVisible) { [UIView setAnimationsEnabled:NO]; [self.navigationController setNavigationBarHidden:NO animated:NO]; navigationBarFrame.origin.y = 0; self.navigationController.navigationBar.frame = navigationBarFrame; self.navigationController.navigationBar.alpha = 0; [UIView setAnimationsEnabled:YES]; navigationBarFrame.origin.y = NIStatusBarHeight(); } else { navigationBarFrame.origin.y = 0; } } if (self.toolbarIsTranslucent) { self.toolbar.frame = toolbarFrame; } if (nil != self.navigationController.navigationBar) { self.navigationController.navigationBar.frame = navigationBarFrame; self.navigationController.navigationBar.alpha = (isVisible ? 1 : 0); } if (animated) { _isAnimatingChrome = YES; [UIView commitAnimations]; } else if (!isVisible) { [self didHideChrome]; } else if (isVisible) { [self didShowChrome]; } } - (void)toggleChromeVisibility { [self setChromeVisibility:(_isChromeHidden || _isAnimatingChrome) animated:YES]; } #pragma mark - UIGestureRecognizer - (void)didTap { SEL selector = @selector(toggleChromeVisibility); if (self.photoAlbumView.zoomingIsEnabled) { // Cancel any previous delayed performs so that we don't stack them. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil]; // We need to delay taking action on the first tap in case a second tap comes in, causing // a double-tap gesture to be recognized and the photo to be zoomed. [self performSelector: selector withObject: nil afterDelay: 0.3]; } else { // When zooming is disabled, double-tap-to-zoom is also disabled so we don't have to // be as careful; just toggle the chrome immediately. [self toggleChromeVisibility]; } } - (void)refreshChromeState { self.previousButton.enabled = [self.photoAlbumView hasPrevious]; self.nextButton.enabled = [self.photoAlbumView hasNext]; [self setChromeTitle]; } - (void)setChromeTitle { self.title = [NSString stringWithFormat:@"%d of %d", (self.photoAlbumView.centerPageIndex + 1), self.photoAlbumView.numberOfPages]; } #pragma mark - NIPhotoAlbumScrollViewDelegate - (void)pagingScrollViewDidScroll:(NIPagingScrollView *)pagingScrollView { if (self.hidesChromeWhenScrolling) { [self setChromeVisibility:NO animated:YES]; } } - (void)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView didZoomIn: (BOOL)didZoomIn { // This delegate method is called after a double-tap gesture, so cancel any pending // single-tap gestures. [NSObject cancelPreviousPerformRequestsWithTarget: self selector: @selector(toggleChromeVisibility) object: nil]; } - (void)pagingScrollViewDidChangePages:(NIPagingScrollView *)pagingScrollView { // We animate the scrubber when the chrome won't disappear as a nice touch. // We don't bother animating if the chrome disappears when scrolling because the user // will barely see the animation happen. [self.photoScrubberView setSelectedPhotoIndex: [pagingScrollView centerPageIndex] animated: !self.hidesChromeWhenScrolling]; [self refreshChromeState]; } #pragma mark - NIPhotoScrubberViewDelegate - (void)photoScrubberViewDidChangeSelection:(NIPhotoScrubberView *)photoScrubberView { [self.photoAlbumView moveToPageAtIndex:photoScrubberView.selectedPhotoIndex animated:NO]; [self refreshChromeState]; } #pragma mark - Actions - (void)didTapNextButton { [self.photoAlbumView moveToNextAnimated:self.animateMovingToNextAndPreviousPhotos]; [self refreshChromeState]; } - (void)didTapPreviousButton { [self.photoAlbumView moveToPreviousAnimated:self.animateMovingToNextAndPreviousPhotos]; [self refreshChromeState]; } #pragma mark - Public - (void)settoolbarIsTranslucent:(BOOL)enabled { _toolbarIsTranslucent = enabled; self.toolbar.translucent = enabled; } - (void)setHidesChromeWhenScrolling:(BOOL)hidesToolbar { _hidesChromeWhenScrolling = hidesToolbar; if (hidesToolbar) { [self addTapGestureToView]; } else { [_tapGesture setEnabled:_chromeCanBeHidden]; } } - (void)setChromeCanBeHidden:(BOOL)canBeHidden { _chromeCanBeHidden = canBeHidden; if (canBeHidden) { [self addTapGestureToView]; } else { self.hidesChromeWhenScrolling = NO; if ([self isViewLoaded]) { // Ensure that the chrome is visible. [self setChromeVisibility:YES animated:NO]; } } } - (void)setScrubberIsEnabled:(BOOL)enabled { if (_scrubberIsEnabled != enabled) { _scrubberIsEnabled = enabled; if ([self isViewLoaded]) { [self updateToolbarItems]; } } } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/photos/src/NimbusPhotos.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusPhotos Nimbus Photos * @{ * * <div id="github" feature="photos"></div> * * Photo viewers are a common, non-trivial feature in many types of iOS apps ranging from * simple photo viewers to apps that fetch photos from an API. The Nimbus photo album viewer * is designed to consume minimal amounts of memory and encourage the use of threads to provide * a high quality user experience that doesn't include any blocking of the UI while images * are loaded from disk or the network. The photo viewer pre-caches images in an album to either * side of the current image so that the user will ideally always have a high-quality * photo experience. * * <h2>Adding the Photos Feature to Your Application</h2> * * The Nimbus Photos feature uses a small number of custom photos that are stored in the * NimbusPhotos bundle. You must add this bundle to your application, ensuring that you select * the "Create Folder References" option and that the bundle is copied in the * "Copy Bundle Resources" phase. * * The bundle can be found at <code>src/photos/resources/NimbusPhotos.bundle</code>. * * * <h2>Feature Breakdown</h2> * * NIPhotoAlbumScrollView - A paged scroll view that implements a data source similar to that * of UITableView. This scroll view consumes minimal amounts of memory and is built to be fast * and responsive. * * NIPhotoScrollView - A single page within the NIPhotoAlbumScrollView. This view implements * the zooming and rotation functionality for a photo. * * NIPhotoScrubberView - A scrubber view for skimming through a set of photos. This view * made its debut by Apple on the iPad in Photos.app. Nimbus' implementation of this view * is built to be responsive and consume little memory. * * NIToolbarPhotoViewController - A skeleton implementation of a view controller that includes * multiple configurable properties. This controller will show a scrubber on the iPad and * next/previous arrows on the iPhone. It also provides support for hiding and showing the * app's chrome. If you wish to use this controller you must simply implement the data source * for the photo album. NetworkPhotoAlbum in the examples/photos directory demos building * a data source that fetches its information from the network. * * * <h2>Architecture</h2> * * The architectural design of the photo album view takes inspiration from UITableView. Images * are requested only when they might become visible and are released when they become * inaccessible again. Each page of the photo album view is a recycled NIPhotoScrollView. * These page views handle zooming and panning within a given photo. The photo album view * NIPhotoAlbumScrollView contains a paging scroll view of these page views and provides * interfaces for maintaining the orientation during rotations. * * The view controller NIToolbarPhotoViewController is provided as a basic implementation of * functionality that is expected from a photo viewer. This includes: a toolbar with next and * previous arrows; auto-rotation support; and toggling the chrome. * * <h3>NIPhotoAlbumScrollView</h3> * * NIPhotoAlbumScrollView is the meat of the Nimbus photo viewer's functionality. Contained * within this view are pages of NIPhotoScrollView views. In your view controller you are * expected to implement the NIPhotoAlbumScrollViewDataSource in order to provide the photo * album view with the necessary information for presenting an album. * * * <h2>Example Applications</h2> * * <h3>Network Photo Albums</h3> * * <a href="https://github.com/jverkoey/nimbus/tree/master/examples/photos/NetworkPhotoAlbums">View the README on GitHub</a> * * This sample application demos the use of the multiple photo APIs to fetch photos from public * photo album and display them in high-definition on the iPad and iPhone. * * The following APIs are currently demoed: * * - Facebook Graph API * - Dribbble Shots * * Sample location: <code>examples/photos/NetworkPhotoAlbums</code> * * * <h2>Screenshots</h2> * * @image html photos-iphone-example1.png "Screenshot of a basic photo album on the iPhone." * * Image source: <a href="http://www.flickr.com/photos/janekm/360669001/">flickr.com/photos/janekm/360669001</a> */ /**@}*/ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPhotoAlbumScrollView.h" #import "NIPhotoAlbumScrollViewDataSource.h" #import "NIPhotoAlbumScrollViewDelegate.h" #import "NIPhotoScrollView.h" #import "NIPhotoScrollViewDelegate.h" #import "NIPhotoScrollViewPhotoSize.h" #import "NIPhotoScrubberView.h" #import "NIToolbarPhotoViewController.h" #import "NimbusPagingScrollView.h" #import "NimbusCore.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/textfield/src/NITextField.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // Originally written by Max Metral // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <UIKit/UIKit.h> /** * UITextField leaves a little to be desired on the visual customization front. * NITextField attempts to solve the most basic of those gaps so that * the CSS subsystem can function properly. */ @interface NITextField : UITextField /** * If non-nil, this color will be used to draw the placeholder text. * If nil, we will use the system default. */ @property (nonatomic, strong) UIColor* placeholderTextColor; /** * If non-nil, this font will be used to draw the placeholder text. * else the text field font will be used. */ @property (nonatomic, strong) UIFont* placeholderFont; /** * The amount to inset the text by, or zero to use default behavior */ @property (nonatomic, assign) UIEdgeInsets textInsets; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/textfield/src/NITextField.m
Objective-C
// // Copyright 2011-2014 NimbusKit // Originally written by Max Metral // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NITextField.h" @implementation NITextField - (void)drawPlaceholderInRect:(CGRect)rect { if (self.placeholderTextColor != nil || self.placeholderFont != nil) { CGContextRef cx = UIGraphicsGetCurrentContext(); CGContextSaveGState(cx); if (self.placeholderTextColor) { [self.placeholderTextColor setFill]; } [self.placeholder drawInRect:rect withFont:(self.placeholderFont != nil ? self.placeholderFont : self.font) lineBreakMode:NSLineBreakByClipping alignment:self.textAlignment]; CGContextRestoreGState(cx); } else { [super drawPlaceholderInRect:rect]; } } - (CGRect)editingRectForBounds:(CGRect)bounds { if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.textInsets)) { return [super editingRectForBounds:bounds]; } return UIEdgeInsetsInsetRect(bounds, self.textInsets); } - (CGRect)textRectForBounds:(CGRect)bounds { if (UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, self.textInsets)) { return [super textRectForBounds:bounds]; } return UIEdgeInsetsInsetRect(bounds, self.textInsets); } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/webcontroller/src/NIWebController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 July 29, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NIPreprocessorMacros.h" /* for weak */ /** * A simple web view controller implementation with a toolbar. * * <h2>Subclassing</h2> * * This view controller implements UIWebViewDelegate. If you want to * implement methods of this delegate then you should take care to call the super implementation * if necessary. The following UIViewWebDelegate methods have implementations in this class: * * @code * - webView:shouldStartLoadWithRequest:navigationType: * - webViewDidStartLoad: * - webViewDidFinishLoad: * - webView:didFailLoadWithError: * @endcode * * This view controller also implements UIActionSheetDelegate. If you want to implement methods of * this delegate then you should take care to call the super implementation if necessary. The * following UIActionSheetDelegate methods have implementations in this class: * * @code * - actionSheet:clickedButtonAtIndex: * - actionSheet:didDismissWithButtonIndex: * @endcode * * In addition to the above methods of the UIActionSheetDelegate, this view controller also provides * the following method, which is invoked prior to presenting the internal action sheet to the user * and allows subclasses to customize the action sheet or even reject to display it (and provide their * own handling instead): * * @code * - shouldPresentActionSheet: * @endcode * * * <h2>Recommended Configurations</h2> * * <h3>Default</h3> * * The default settings will create a toolbar with the default tint color, which is normally * light blue on the iPhone and gray on the iPad. * * * <h3>Colored Toolbar</h3> * * The following settings will change the toolbar tint color (in this case black) * * @code * [webController setToolbarTintColor:[UIColor blackColor]]; * @endcode * * @ingroup NimbusWebController */ @interface NIWebController : UIViewController <UIWebViewDelegate, UIActionSheetDelegate> // Designated initializer. - (id)initWithRequest:(NSURLRequest *)request; - (id)initWithURL:(NSURL *)URL; - (NSURL *)URL; - (void)openURL:(NSURL*)URL; - (void)openRequest:(NSURLRequest*)request; - (void)openHTMLString:(NSString*)htmlString baseURL:(NSURL*)baseUrl; @property (nonatomic, readonly, strong) UIToolbar* toolbar; @property (nonatomic, assign, getter = isToolbarHidden) BOOL toolbarHidden; @property (nonatomic, weak) UIColor* toolbarTintColor; @property (nonatomic, readonly, strong) UIWebView* webView; // Subclassing - (BOOL)shouldPresentActionSheet:(UIActionSheet *)actionSheet; @property (nonatomic, strong) NSURL* actionSheetURL; @end /** @name Creating a Web Controller */ /** * Initializes a newly allocated web controller with a given request. * * Once the controller is presented it will begin loading the given request. * * This is the designated initializer. * * @fn NIWebController::initWithRequest: */ /** * Initializes a newly allocated web controller with a given URL to request. * * Once the controller is presented it will begin loading the given URL. * * @fn NIWebController::initWithURL: */ /** @name Accessing the Request Attributes */ /** * The current web view URL. * * If the web view is currently loading a URL then the loading URL is returned. * Otherwise this will be the last URL that was loaded. * * @fn NIWebController::URL: */ /** @name Loading a Request */ /** * Loads a request with the given URL in the web view. * * @fn NIWebController::openURL: */ /** * Load the given request using UIWebView's loadRequest:. * * @param request A URL request identifying the location of the content to load. * * @fn NIWebController::openRequest: */ /** * Load the given request using UIWebView's loadHTMLString:baseURL:. * * @param htmlString The content for the main page. * @param baseUrl The base URL for the content. * * @fn NIWebController::openHTMLString:baseURL: */ /** @name Accessing the Toolbar */ /** * The toolbar. * * @fn NIWebController::toolbar */ /** * The visibility of the toolbar. * * If the toolbar is hidden then the web view will take up the controller's entire view. * * @fn NIWebController::toolbarHidden */ /** * The tint color of the toolbar. * * @fn NIWebController::toolbarTintColor */ /** @name Accessing the Web View */ /** * The internal web view. * * @fn NIWebController::webView */ /** @name Subclassing the Web Controller */ /** * This message is called in response to the user clicking the action toolbar button. * * You can provide your own implementation in your subclass and customize the actionSheet * that is shown to the user or even cancel the presentation of the @c actionSheet by * returning NO from your implementation. * * @param actionSheet The UIActionSheet that will be presented to the user. * @return YES to present the actionSheet, NO if you want to perform a custom action. * @fn NIWebController::shouldPresentActionSheet: */
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/webcontroller/src/NIWebController.m
Objective-C
// // Copyright 2011-2014 NimbusKit // // Forked from Three20 July 29, 2011 - Copyright 2009-2011 Facebook // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #import "NIWebController.h" #import "NimbusCore.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "Nimbus requires ARC support." #endif @interface NIWebController() @property (nonatomic, strong) UIWebView* webView; @property (nonatomic, strong) UIToolbar* toolbar; @property (nonatomic, strong) UIActionSheet* actionSheet; @property (nonatomic, strong) UIBarButtonItem* backButton; @property (nonatomic, strong) UIBarButtonItem* forwardButton; @property (nonatomic, strong) UIBarButtonItem* refreshButton; @property (nonatomic, strong) UIBarButtonItem* stopButton; @property (nonatomic, strong) UIBarButtonItem* actionButton; @property (nonatomic, strong) UIBarButtonItem* activityItem; @property (nonatomic, strong) NSURL* loadingURL; @property (nonatomic, strong) NSURLRequest* loadRequest; @end @implementation NIWebController - (void)dealloc { _actionSheet.delegate = nil; _webView.delegate = nil; } - (id)initWithRequest:(NSURLRequest *)request { if ((self = [super initWithNibName:nil bundle:nil])) { self.hidesBottomBarWhenPushed = YES; if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) { self.edgesForExtendedLayout = UIRectEdgeNone; } [self openRequest:request]; } return self; } - (id)initWithURL:(NSURL *)URL { return [self initWithRequest:[NSURLRequest requestWithURL:URL]]; } - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { return [self initWithRequest:nil]; } #pragma mark - Private - (void)didTapBackButton { [self.webView goBack]; } - (void)didTapForwardButton { [self.webView goForward]; } - (void)didTapRefreshButton { [self.webView reload]; } - (void)didTapStopButton { [self.webView stopLoading]; } - (void)didTapShareButton { // Dismiss the action menu if the user taps the action button again on the iPad. if ([self.actionSheet isVisible]) { // It shouldn't be possible to tap the share action button again on anything but the iPad. NIDASSERT(NIIsPad()); [self.actionSheet dismissWithClickedButtonIndex:[self.actionSheet cancelButtonIndex] animated:YES]; // We remove the action sheet here just in case the delegate isn't properly implemented. self.actionSheet.delegate = nil; self.actionSheet = nil; self.actionSheetURL = nil; // Don't show the menu again. return; } // Remember the URL at this point self.actionSheetURL = [self.URL copy]; if (nil == self.actionSheet) { self.actionSheet = [[UIActionSheet alloc] initWithTitle:[self.actionSheetURL absoluteString] delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; // Let -shouldPresentActionSheet: setup the action sheet if (![self shouldPresentActionSheet:self.actionSheet] || self.actionSheet.numberOfButtons == 0) { // A subclass decided to handle the action in another way self.actionSheet = nil; self.actionSheetURL = nil; return; } // Add "Cancel" button except for iPads if (!NIIsPad()) { [self.actionSheet setCancelButtonIndex:[self.actionSheet addButtonWithTitle:NSLocalizedString(@"Cancel", @"")]]; } } if (NIIsPad()) { [self.actionSheet showFromBarButtonItem:self.actionButton animated:YES]; } else { [self.actionSheet showInView:self.view]; } } - (void)updateToolbarWithOrientation:(UIInterfaceOrientation)interfaceOrientation { if (!self.toolbarHidden) { CGRect toolbarFrame = self.toolbar.frame; toolbarFrame.size.height = NIToolbarHeightForOrientation(interfaceOrientation); toolbarFrame.origin.y = self.view.bounds.size.height - toolbarFrame.size.height; self.toolbar.frame = toolbarFrame; CGRect webViewFrame = self.webView.frame; webViewFrame.size.height = self.view.bounds.size.height - toolbarFrame.size.height; self.webView.frame = webViewFrame; } else { self.webView.frame = self.view.bounds; } } #pragma mark - UIViewController - (void)updateWebViewFrame { if (self.toolbarHidden) { self.webView.frame = self.view.bounds; } else { self.webView.frame = NIRectContract(self.view.bounds, 0, self.toolbar.frame.size.height); } } - (void)loadView { [super loadView]; CGRect bounds = self.view.bounds; CGFloat toolbarHeight = NIToolbarHeightForOrientation(NIInterfaceOrientation()); CGRect toolbarFrame = CGRectMake(0, bounds.size.height - toolbarHeight, bounds.size.width, toolbarHeight); self.toolbar = [[UIToolbar alloc] initWithFrame:toolbarFrame]; self.toolbar.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth); self.toolbar.tintColor = self.toolbarTintColor; self.toolbar.hidden = self.toolbarHidden; UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite]; [spinner startAnimating]; self.activityItem = [[UIBarButtonItem alloc] initWithCustomView:spinner]; UIImage* backIcon = [UIImage imageWithContentsOfFile: NIPathForBundleResource(nil, @"NimbusWebController.bundle/gfx/backIcon.png")]; // We weren't able to find the forward or back icons in your application's resources. // Ensure that you've dragged the NimbusWebController.bundle from src/webcontroller/resources //into your application with the "Create Folder References" option selected. You can verify that // you've done this correctly by expanding the NimbusPhotos.bundle file in your project // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being // copied in the Copy Bundle Resources phase. NIDASSERT(nil != backIcon); self.backButton = [[UIBarButtonItem alloc] initWithImage:backIcon style:UIBarButtonItemStylePlain target:self action:@selector(didTapBackButton)]; self.backButton.tag = 2; self.backButton.enabled = NO; UIImage* forwardIcon = [UIImage imageWithContentsOfFile: NIPathForBundleResource(nil, @"NimbusWebController.bundle/gfx/forwardIcon.png")]; // We weren't able to find the forward or back icons in your application's resources. // Ensure that you've dragged the NimbusWebController.bundle from src/webcontroller/resources // into your application with the "Create Folder References" option selected. You can verify that // you've done this correctly by expanding the NimbusPhotos.bundle file in your project // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being // copied in the Copy Bundle Resources phase. NIDASSERT(nil != forwardIcon); self.forwardButton = [[UIBarButtonItem alloc] initWithImage:forwardIcon style:UIBarButtonItemStylePlain target:self action:@selector(didTapForwardButton)]; self.forwardButton.tag = 1; self.forwardButton.enabled = NO; self.refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemRefresh target:self action:@selector(didTapRefreshButton)]; self.refreshButton.tag = 3; self.stopButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemStop target:self action:@selector(didTapStopButton)]; self.stopButton.tag = 3; self.actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAction target:self action:@selector(didTapShareButton)]; UIBarItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil]; self.toolbar.items = [NSArray arrayWithObjects: self.backButton, flexibleSpace, self.forwardButton, flexibleSpace, self.refreshButton, flexibleSpace, self.actionButton, nil]; self.webView = [[UIWebView alloc] initWithFrame:CGRectZero]; [self updateWebViewFrame]; self.webView.delegate = self; self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); self.webView.scalesPageToFit = YES; if ([UIColor respondsToSelector:@selector(underPageBackgroundColor)]) { self.webView.backgroundColor = [UIColor underPageBackgroundColor]; } [self.view addSubview:self.webView]; [self.view addSubview:self.toolbar]; if (nil != self.loadRequest) { [self.webView loadRequest:self.loadRequest]; } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self updateToolbarWithOrientation:self.interfaceOrientation]; } - (void)viewWillDisappear:(BOOL)animated { // If the browser launched the media player, it steals the key window and never gives it // back, so this is a way to try and fix that. [self.view.window makeKeyWindow]; [super viewWillDisappear:animated]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return NIIsSupportedOrientation(interfaceOrientation); } - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; [self updateToolbarWithOrientation:toInterfaceOrientation]; } #pragma mark - UIWebViewDelegate - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { self.loadingURL = [request.mainDocumentURL copy]; self.backButton.enabled = [self.webView canGoBack]; self.forwardButton.enabled = [self.webView canGoForward]; return YES; } - (void)webViewDidStartLoad:(UIWebView*)webView { self.title = NSLocalizedString(@"Loading...", @""); if (!self.navigationItem.rightBarButtonItem) { [self.navigationItem setRightBarButtonItem:self.activityItem animated:YES]; } NSInteger buttonIndex = 0; for (UIBarButtonItem* button in self.toolbar.items) { if (button.tag == 3) { NSMutableArray* newItems = [NSMutableArray arrayWithArray:self.toolbar.items]; [newItems replaceObjectAtIndex:buttonIndex withObject:self.stopButton]; self.toolbar.items = newItems; break; } ++buttonIndex; } self.backButton.enabled = [self.webView canGoBack]; self.forwardButton.enabled = [self.webView canGoForward]; } - (void)webViewDidFinishLoad:(UIWebView*)webView { self.loadingURL = nil; self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]; if (self.navigationItem.rightBarButtonItem == self.activityItem) { [self.navigationItem setRightBarButtonItem:nil animated:YES]; } NSInteger buttonIndex = 0; for (UIBarButtonItem* button in self.toolbar.items) { if (button.tag == 3) { NSMutableArray* newItems = [NSMutableArray arrayWithArray:self.toolbar.items]; [newItems replaceObjectAtIndex:buttonIndex withObject:self.refreshButton]; self.toolbar.items = newItems; break; } ++buttonIndex; } self.backButton.enabled = [self.webView canGoBack]; self.forwardButton.enabled = [self.webView canGoForward]; } - (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error { self.loadingURL = nil; [self webViewDidFinishLoad:webView]; } #pragma mark - UIActionSheetDelegate - (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (actionSheet == self.actionSheet) { if (buttonIndex == 0) { [[UIApplication sharedApplication] openURL:self.actionSheetURL]; } else if (buttonIndex == 1) { [[UIPasteboard generalPasteboard] setURL:self.actionSheetURL]; } } } - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { if (actionSheet == self.actionSheet) { self.actionSheet.delegate = nil; self.actionSheet = nil; self.actionSheetURL = nil; } } #pragma mark - Public - (NSURL *)URL { return self.loadingURL ? self.loadingURL : self.webView.request.mainDocumentURL; } - (void)openURL:(NSURL*)URL { NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL]; [self openRequest:request]; } - (void)openRequest:(NSURLRequest *)request { self.loadRequest = request; if ([self isViewLoaded]) { if (nil != request) { [self.webView loadRequest:request]; } else { [self.webView stopLoading]; } } } - (void)openHTMLString:(NSString*)htmlString baseURL:(NSURL*)baseUrl { NIDASSERT([self isViewLoaded]); [_webView loadHTMLString:htmlString baseURL:baseUrl]; } - (void)setToolbarHidden:(BOOL)hidden { _toolbarHidden = hidden; if ([self isViewLoaded]) { self.toolbar.hidden = hidden; [self updateWebViewFrame]; } } - (void)setToolbarTintColor:(UIColor*)color { if (color != _toolbarTintColor) { _toolbarTintColor = color; } if ([self isViewLoaded]) { self.toolbar.tintColor = color; } } - (BOOL)shouldPresentActionSheet:(UIActionSheet *)actionSheet { if (actionSheet == self.actionSheet && nil != self.actionSheetURL) { [self.actionSheet addButtonWithTitle:NSLocalizedString(@"Open in Safari", @"")]; [self.actionSheet addButtonWithTitle:NSLocalizedString(@"Copy URL", @"")]; } return YES; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Nimbus/src/webcontroller/src/NimbusWebController.h
C/C++ Header
// // Copyright 2011-2014 NimbusKit // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /** * @defgroup NimbusWebController Nimbus Web Controller * @{ * * <div id="github" feature="webcontroller"></div> * * This controller presents a UIWebView with a toolbar containing basic chrome for interacting * with it. The chrome shows forward, back, stop and refresh buttons on a toolbar aligned * to the bottom of the view controller's view. The toolbar includes an option to open the * URL in Safari. If the controller is shown in a navigation controller, self.title will * show the current web page's title. A spinner will be shown in the navigation bar's right * bar button area if there are any active requests. * * @image html webcontroller-iphone-example1.png "Screenshot of a basic web controller on the iPhone" * * <h2>Minimum Requirements</h2> * * Required frameworks: * * - Foundation.framework * - UIKit.framework * * Minimum Operating System: <b>iOS 4.0</b> * * Source located in <code>src/webcontroller/src</code> * * <h2>Adding the Web Controller to Your Application</h2> * * The web controller uses a small number of custom icons that are stored in the NimbusWebController * bundle. You must add this bundle to your application, ensuring that you select the "Create Folder * References" option and that the bundle is copied in the "Copy Bundle Resources" phase. * * The bundle can be found at <code>src/webcontroller/resources/NimbusWebController.bundle</code>. * * @}*/ #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "NimbusCore.h" #import "NIWebController.h"
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Placeholder/Pod/Classes/Placeholder.h
C/C++ Header
// // ALFLEXBOXUtils.h // all_layouts // // Created by xiekw on 15/7/6. // Copyright (c) 2015年 xiekw. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> typedef void (^PlaceholderBlock)(NSArray *models, NSError *error); @interface UIColor (PH_Colorful) + (UIColor *)randomColor; + (UIColor *)randomColorWithAlpha:(CGFloat)alpha; @end @interface Placeholder : NSObject + (NSString *)textWithRange:(NSRange)range; + (UIImage *)imageWithSize:(CGSize)size; + (NSString *)imageURL; + (NSString *)paragraph; @end @interface PlaceholderModel : NSObject + (instancetype)randomModel; + (NSArray *)randomModelWithRange:(NSRange)range; + (void)asyncRandomModelWithRange:(NSRange)range completionBlock:(PlaceholderBlock)block; @end @interface PHFeedUser : PlaceholderModel @property (nonatomic, strong) NSString *username; @property (nonatomic, strong) NSString *bio; @property (nonatomic, strong) NSString *avatarURL; + (instancetype)randomModel; @end @interface PHFeedComment : PlaceholderModel @property (nonatomic, strong) PHFeedUser *user; @property (nonatomic, strong) NSString *commentDate; @property (nonatomic, strong) NSString *commentContent; @property (nonatomic, strong) NSArray *imageURLs; + (instancetype)randomModel; @end @interface PHFeed : PlaceholderModel @property (nonatomic, strong) PHFeedUser *user; @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSString *subTitle; @property (nonatomic, strong) NSString *content; @property (nonatomic, strong) NSArray *tags; @property (nonatomic, strong) NSArray *comments; @property (nonatomic, strong) NSArray *imageURLs; @property (nonatomic, assign) CGFloat currentPrice; @property (nonatomic, assign) CGFloat originPrice; @property (nonatomic, assign) NSUInteger soldedCount; @property (nonatomic, assign, getter=isLiked) BOOL liked; + (instancetype)randomModel; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Placeholder/Pod/Classes/Placeholder.m
Objective-C
// // ALFLEXBOXUtils.m // all_layouts // // Created by xiekw on 15/7/6. // Copyright (c) 2015年 xiekw. All rights reserved. // #import "Placeholder.h" static NSString * const kEnglishContent = @"The Réunion parrot or Dubois's parrot (Necropsittacus borbonicus) is a hypothetical extinct species of parrot based on descriptions of birds from the Mascarene island of Réunion. Its existence has been inferred from the travel report of Dubois in 1674 who described it as having a Body the size of a large pigeon, green; head, tail and upper part of wings the colour of fire. No remains have been found of this supposed species, and its existence seems doubtful."; static NSString * const kChineseContent = @"盼望着,盼望着,东风来了,春天的脚步近了。一切都象刚睡醒的样子,欣欣然张开了眼。山朗润起来了,水涨起来了,太阳的脸红起来了。\n小草偷偷地从土里钻出来,嫩嫩的,绿绿的。园子里,田野里,瞧去,一大片一大片满是的。坐着,趟着,打两个滚,踢几脚球,赛几趟跑,捉几回迷藏。风轻悄悄的,草软绵绵的。\n桃树、杏树、梨树,你不让我,我不让你,都开满了花赶趟儿。红的像火,粉的像霞,白的像雪。花里带着甜味儿,闭了眼,树上仿佛已经满是桃儿、杏儿、梨儿!花下成千成百的蜜蜂嗡嗡地闹着,大小的蝴蝶飞来飞去。野花遍地是:杂样儿,有名字的,没名字的,散在草丛里像眼睛,像星星,还眨呀眨的。\n“吹面不寒杨柳风”,不错的,像母亲的手抚摸着你。风里带来些新翻的泥土气息,混着青草味儿,还有各种花的香都在微微润湿的空气里酝酿。鸟儿将窠巢安在繁花嫩叶当中,高兴起来了,呼朋引伴地卖弄清脆的喉咙,唱出宛转的曲子,与轻风流水应和着。牛背上牧童的短笛,这时候也成天嘹亮地响。\n雨是最寻常的,一下就是两三天。可别恼。看,像牛毛,像花针,像细丝,密密地斜织着,人家屋顶上全笼着一层薄烟。树叶子却绿得发亮,小草儿也青得逼你的眼。傍晚时候,上灯了,一点点黄晕的光,烘托出一片安静而和平的夜。乡下去,小路上,石桥边,有撑起伞慢慢走着的人;还有地里工作的农夫,披着蓑,戴着笠。他们的房屋,稀稀疏疏的,在雨里静默着。\n天上风筝渐渐多了,地上孩子也多了。城里乡下,家家户户,老老小小,也赶趟儿似的,一个个都出来了。舒活舒活筋骨,抖擞精神,各做各的一份儿事去了。“一年之计在于春”,刚起头儿,有的是工夫,有的是希望。\n春天像刚落地的娃娃,从头里脚是新的,它生长着。\n春天像小姑娘,花枝招展的,笑着,走着。\n春天像健壮的青年,有铁一般的胳膊和腰脚,领着我们上前去。"; static inline CGFloat RandomFloatBetweenLowAndHigh(CGFloat low, CGFloat high) { CGFloat diff = high - low; return (((CGFloat) rand() / RAND_MAX) * diff) + low; } static inline NSString *RandomUserName() { NSMutableString *ms = [NSMutableString new]; for (u_int32_t i = 0; i < arc4random_uniform(10) + 5; ++i) { [ms appendFormat:@"%c", arc4random_uniform('z' - 'a') + 'a']; } return ms; } static inline BOOL RandomBool() { return arc4random_uniform(2) == 1; } static inline NSUInteger RandomIntBetweenLowAndHigh(NSUInteger low, NSUInteger high) { u_int32_t diff = (u_int32_t)(high - low); return (arc4random_uniform(diff)) + low; } static inline NSString *RandomTextWithRange(NSInteger min, NSInteger max, NSString *sample) { NSInteger textLength = sample.length; NSInteger location = RandomIntBetweenLowAndHigh(0, textLength); NSInteger length = MIN(RandomIntBetweenLowAndHigh(min, max), textLength - location); return [sample substringWithRange:NSMakeRange(location, length)]; } static inline NSArray *RandomObjectArrayWithRandomCountBetween(NSUInteger low, NSUInteger high, id (^create)()) { NSUInteger count = RandomIntBetweenLowAndHigh(low, high); NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:count]; for (NSUInteger i = 0; i < count; i ++) { id obj; if (create) { obj = create(); } if (!obj) { obj = RandomTextWithRange(2, 10, kEnglishContent); } [mArray addObject:obj]; } return mArray; } static inline NSDateFormatter *dateFormatter() { static dispatch_once_t onceToken; static NSDateFormatter *formatter = nil; dispatch_once(&onceToken, ^{ formatter = [NSDateFormatter new]; [formatter setDateFormat:@"y-L-d, H:m:s"]; }); return formatter; } @implementation UIColor (PH_Colorful) + (UIColor *)randomColor { return [self randomColorWithAlpha:1.0]; } + (UIColor *)randomColorWithAlpha:(CGFloat)alpha { CGFloat red = arc4random_uniform(255) / 255.0; CGFloat green = arc4random_uniform(255) / 255.0; CGFloat blue = arc4random_uniform(255) / 255.0; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } @end @implementation Placeholder + (NSArray *)textPlaceholders { static dispatch_once_t onceToken; static NSArray *texts; dispatch_once(&onceToken, ^{ texts = @[ @"Kitty ipsum dolor sit amet, purr sleep on your face lay down in your way biting, sniff tincidunt a etiam fluffy fur judging you stuck in a tree kittens.", @"Lick tincidunt a biting eat the grass, egestas enim ut lick leap puking climb the curtains lick.", @"Lick quis nunc toss the mousie vel, tortor pellentesque sunbathe orci turpis non tail flick suscipit sleep in the sink.", @"Orci turpis litter box et stuck in a tree, egestas ac tempus et aliquam elit.", @"Hairball iaculis dolor dolor neque, nibh adipiscing vehicula egestas dolor aliquam.", @"Sunbathe fluffy fur tortor faucibus pharetra jump, enim jump on the table I don't like that food catnip toss the mousie scratched.", @"Quis nunc nam sleep in the sink quis nunc purr faucibus, chase the red dot consectetur bat sagittis.", @"Lick tail flick jump on the table stretching purr amet, rhoncus scratched jump on the table run.", @"Suspendisse aliquam vulputate feed me sleep on your keyboard, rip the couch faucibus sleep on your keyboard tristique give me fish dolor.", @"Rip the couch hiss attack your ankles biting pellentesque puking, enim suspendisse enim mauris a.", @"Sollicitudin iaculis vestibulum toss the mousie biting attack your ankles, puking nunc jump adipiscing in viverra.", @"Nam zzz amet neque, bat tincidunt a iaculis sniff hiss bibendum leap nibh.", @"Chase the red dot enim puking chuf, tristique et egestas sniff sollicitudin pharetra enim ut mauris a.", @"Sagittis scratched et lick, hairball leap attack adipiscing catnip tail flick iaculis lick.", @"Neque neque sleep in the sink neque sleep on your face, climb the curtains chuf tail flick sniff tortor non.", @"Ac etiam kittens claw toss the mousie jump, pellentesque rhoncus litter box give me fish adipiscing mauris a.", @"Pharetra egestas sunbathe faucibus ac fluffy fur, hiss feed me give me fish accumsan.", @"Tortor leap tristique accumsan rutrum sleep in the sink, amet sollicitudin adipiscing dolor chase the red dot.", @"Knock over the lamp pharetra vehicula sleep on your face rhoncus, jump elit cras nec quis quis nunc nam.", @"Sollicitudin feed me et ac in viverra catnip, nunc eat I don't like that food iaculis give me fish.", ]; }); return texts; } + (NSString *)textWithRange:(NSRange)range { NSUInteger min = range.location; NSUInteger max = range.length; return RandomTextWithRange(min, max, kEnglishContent); } + (NSString *)paragraph { NSArray *placeholders = [self textPlaceholders]; u_int32_t ipsumCount = (u_int32_t)[placeholders count]; u_int32_t location = arc4random_uniform(ipsumCount); u_int32_t length = arc4random_uniform(ipsumCount - location); NSMutableString *string = [placeholders[location] mutableCopy]; for (u_int32_t i = location + 1; i < location + length; i++) { [string appendString:(i % 2 == 0) ? @"\n" : @" "]; [string appendString:placeholders[i]]; } return string; } + (UIImage *)imageWithSize:(CGSize)size { CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [[UIColor randomColor] CGColor]); CGContextFillRect(context, rect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } // lorem ipsum text courtesy http://kittyipsum.com/ <3 + (NSString *)imageURL { u_int32_t deltaX = arc4random_uniform(10) - 5; u_int32_t deltaY = arc4random_uniform(10) - 5; CGSize size = CGSizeMake(350 + 2 * deltaX, 350 + 4 * deltaY); NSString *imageURL = [NSString stringWithFormat:@"http://placekitten.com/%zd/%zd", (NSInteger)roundl(size.width), (NSInteger)roundl(size.height)]; return imageURL; } @end @implementation PlaceholderModel + (instancetype)randomModel { return [[self class] new]; } + (NSArray *)randomModelWithRange:(NSRange)range { NSUInteger min = range.location; NSUInteger max = range.length; return RandomObjectArrayWithRandomCountBetween(min, max, ^id{ return [[self class] randomModel]; }); } + (void)asyncRandomModelWithRange:(NSRange)range completionBlock:(PlaceholderBlock)block { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RandomFloatBetweenLowAndHigh(2, 10.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ BOOL needError = arc4random_uniform(10) == 1; NSError *error = needError ? [NSError new] : nil; NSArray *objects = nil; if (!needError) { objects = [[self class] randomModelWithRange:range]; } block(objects, error); }); } @end @implementation PHFeedUser + (instancetype)randomModel { PHFeedUser *user = [[self class] new]; user.username = RandomUserName(); user.bio = RandomBool() ? RandomTextWithRange(5, 140, kEnglishContent) : nil; user.avatarURL = [Placeholder imageURL]; return user; } @end @implementation PHFeedComment + (instancetype)randomModel { PHFeedComment *comment = [[self class] new]; comment.user = [PHFeedUser randomModel]; comment.commentDate = [dateFormatter() stringFromDate:[NSDate date]]; comment.commentContent = [Placeholder paragraph]; comment.imageURLs = RandomBool() ? RandomObjectArrayWithRandomCountBetween(2, 9, ^id{ return [Placeholder imageURL]; }) : nil; return comment; } @end @implementation PHFeed + (instancetype)randomModel { PHFeed *model = [PHFeed new]; model.user = [PHFeedUser randomModel]; model.originPrice = RandomFloatBetweenLowAndHigh(50.0, 10000.0); model.currentPrice = RandomFloatBetweenLowAndHigh(50, model.originPrice); model.soldedCount = RandomIntBetweenLowAndHigh(50, 100000); model.content = [Placeholder paragraph]; model.title = RandomTextWithRange(10, 50, kEnglishContent);; model.subTitle = RandomTextWithRange(30, 200.0, kEnglishContent); model.tags = RandomObjectArrayWithRandomCountBetween(4, 10, ^id{ return RandomTextWithRange(2, 15, kEnglishContent); }); model.comments = RandomObjectArrayWithRandomCountBetween(10, 50, ^id{ return [PHFeedComment randomModel]; }); model.imageURLs = RandomObjectArrayWithRandomCountBetween(3, 6, ^id{ return [Placeholder imageURL]; }); model.liked = RandomBool(); return model; } @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/RegexKitLite/RegexKitLite/RegexKitLite.h
C/C++ Header
// // RegexKitLite.h // http://regexkit.sourceforge.net/ // Licensed under the terms of the BSD License, as specified below. // /* Copyright (c) 2008-2010, John Engelhart All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Zang Industries nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef __OBJC__ #import <Foundation/NSArray.h> #import <Foundation/NSError.h> #import <Foundation/NSObjCRuntime.h> #import <Foundation/NSRange.h> #import <Foundation/NSString.h> #endif // __OBJC__ #include <limits.h> #include <stdint.h> #include <sys/types.h> #include <TargetConditionals.h> #include <AvailabilityMacros.h> #ifdef __cplusplus extern "C" { #endif #ifndef REGEXKITLITE_VERSION_DEFINED #define REGEXKITLITE_VERSION_DEFINED #define _RKL__STRINGIFY(b) #b #define _RKL_STRINGIFY(a) _RKL__STRINGIFY(a) #define _RKL_JOIN_VERSION(a,b) _RKL_STRINGIFY(a##.##b) #define _RKL_VERSION_STRING(a,b) _RKL_JOIN_VERSION(a,b) #define REGEXKITLITE_VERSION_MAJOR 4 #define REGEXKITLITE_VERSION_MINOR 0 #define REGEXKITLITE_VERSION_CSTRING _RKL_VERSION_STRING(REGEXKITLITE_VERSION_MAJOR, REGEXKITLITE_VERSION_MINOR) #define REGEXKITLITE_VERSION_NSSTRING @REGEXKITLITE_VERSION_CSTRING #endif // REGEXKITLITE_VERSION_DEFINED #if !defined(RKL_BLOCKS) && defined(NS_BLOCKS_AVAILABLE) && (NS_BLOCKS_AVAILABLE == 1) #define RKL_BLOCKS 1 #endif #if defined(RKL_BLOCKS) && (RKL_BLOCKS == 1) #define _RKL_BLOCKS_ENABLED 1 #endif // defined(RKL_BLOCKS) && (RKL_BLOCKS == 1) #if defined(_RKL_BLOCKS_ENABLED) && !defined(__BLOCKS__) #warning RegexKitLite support for Blocks is enabled, but __BLOCKS__ is not defined. This compiler may not support Blocks, in which case the behavior is undefined. This will probably cause numerous compiler errors. #endif // defined(_RKL_BLOCKS_ENABLED) && !defined(__BLOCKS__) // For Mac OS X < 10.5. #ifndef NSINTEGER_DEFINED #define NSINTEGER_DEFINED #if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) typedef long NSInteger; typedef unsigned long NSUInteger; #define NSIntegerMin LONG_MIN #define NSIntegerMax LONG_MAX #define NSUIntegerMax ULONG_MAX #else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) typedef int NSInteger; typedef unsigned int NSUInteger; #define NSIntegerMin INT_MIN #define NSIntegerMax INT_MAX #define NSUIntegerMax UINT_MAX #endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) #endif // NSINTEGER_DEFINED #ifndef RKLREGEXOPTIONS_DEFINED #define RKLREGEXOPTIONS_DEFINED // These must be identical to their ICU regex counterparts. See http://www.icu-project.org/userguide/regexp.html enum { RKLNoOptions = 0, RKLCaseless = 2, RKLComments = 4, RKLDotAll = 32, RKLMultiline = 8, RKLUnicodeWordBoundaries = 256 }; typedef uint32_t RKLRegexOptions; // This must be identical to the ICU 'flags' argument type. #endif // RKLREGEXOPTIONS_DEFINED #ifndef RKLREGEXENUMERATIONOPTIONS_DEFINED #define RKLREGEXENUMERATIONOPTIONS_DEFINED enum { RKLRegexEnumerationNoOptions = 0UL, RKLRegexEnumerationCapturedStringsNotRequired = 1UL << 9, RKLRegexEnumerationReleaseStringReturnedByReplacementBlock = 1UL << 10, RKLRegexEnumerationFastCapturedStringsXXX = 1UL << 11, }; typedef NSUInteger RKLRegexEnumerationOptions; #endif // RKLREGEXENUMERATIONOPTIONS_DEFINED #ifndef _REGEXKITLITE_H_ #define _REGEXKITLITE_H_ #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465) #define RKL_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) #else #define RKL_DEPRECATED_ATTRIBUTE #endif #if defined(NS_REQUIRES_NIL_TERMINATION) #define RKL_REQUIRES_NIL_TERMINATION NS_REQUIRES_NIL_TERMINATION #else // defined(NS_REQUIRES_NIL_TERMINATION) #define RKL_REQUIRES_NIL_TERMINATION #endif // defined(NS_REQUIRES_NIL_TERMINATION) // This requires a few levels of rewriting to get the desired results. #define _RKL_CONCAT_2(c,d) c ## d #define _RKL_CONCAT(a,b) _RKL_CONCAT_2(a,b) #ifdef RKL_PREPEND_TO_METHODS #define RKL_METHOD_PREPEND(x) _RKL_CONCAT(RKL_PREPEND_TO_METHODS, x) #else // RKL_PREPEND_TO_METHODS #define RKL_METHOD_PREPEND(x) x #endif // RKL_PREPEND_TO_METHODS // If it looks like low memory notifications might be available, add code to register and respond to them. // This is (should be) harmless if it turns out that this isn't the case, since the notification that we register for, // UIApplicationDidReceiveMemoryWarningNotification, is dynamically looked up via dlsym(). #if ((defined(TARGET_OS_EMBEDDED) && (TARGET_OS_EMBEDDED != 0)) || (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0))) && (!defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) || (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS != 0)) #define RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS 1 #endif #ifdef __OBJC__ // NSException exception name. extern NSString * const RKLICURegexException; // NSError error domains and user info keys. extern NSString * const RKLICURegexErrorDomain; extern NSString * const RKLICURegexEnumerationOptionsErrorKey; extern NSString * const RKLICURegexErrorCodeErrorKey; extern NSString * const RKLICURegexErrorNameErrorKey; extern NSString * const RKLICURegexLineErrorKey; extern NSString * const RKLICURegexOffsetErrorKey; extern NSString * const RKLICURegexPreContextErrorKey; extern NSString * const RKLICURegexPostContextErrorKey; extern NSString * const RKLICURegexRegexErrorKey; extern NSString * const RKLICURegexRegexOptionsErrorKey; extern NSString * const RKLICURegexReplacedCountErrorKey; extern NSString * const RKLICURegexReplacedStringErrorKey; extern NSString * const RKLICURegexReplacementStringErrorKey; extern NSString * const RKLICURegexSubjectRangeErrorKey; extern NSString * const RKLICURegexSubjectStringErrorKey; @interface NSString (RegexKitLiteAdditions) + (void)RKL_METHOD_PREPEND(clearStringCache); // Although these are marked as deprecated, a bug in GCC prevents a warning from being issues for + class methods. Filed bug with Apple, #6736857. + (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex RKL_DEPRECATED_ATTRIBUTE; + (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex options:(RKLRegexOptions)options error:(NSError **)error RKL_DEPRECATED_ATTRIBUTE; - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex; - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex range:(NSRange)range; - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex; - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex inRange:(NSRange)range; - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error; - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex; - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex capture:(NSInteger)capture; - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex inRange:(NSRange)range; - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex; - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex capture:(NSInteger)capture; - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex inRange:(NSRange)range; - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement; - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange; - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error; //// >= 3.0 - (NSInteger)RKL_METHOD_PREPEND(captureCount); - (NSInteger)RKL_METHOD_PREPEND(captureCountWithOptions):(RKLRegexOptions)options error:(NSError **)error; - (BOOL)RKL_METHOD_PREPEND(isRegexValid); - (BOOL)RKL_METHOD_PREPEND(isRegexValidWithOptions):(RKLRegexOptions)options error:(NSError **)error; - (void)RKL_METHOD_PREPEND(flushCachedRegexData); - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex; - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex capture:(NSInteger)capture; - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex range:(NSRange)range; - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range capture:(NSInteger)capture error:(NSError **)error; - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex; - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range; - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex; - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range; - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error; //// >= 4.0 - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList; - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count; - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... RKL_REQUIRES_NIL_TERMINATION; - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList; - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count; #ifdef _RKL_BLOCKS_ENABLED - (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; #endif // _RKL_BLOCKS_ENABLED @end @interface NSMutableString (RegexKitLiteAdditions) - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement; - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange; - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error; //// >= 4.0 #ifdef _RKL_BLOCKS_ENABLED - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block; #endif // _RKL_BLOCKS_ENABLED @end #endif // __OBJC__ #endif // _REGEXKITLITE_H_ #ifdef __cplusplus } // extern "C" #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/RegexKitLite/RegexKitLite/RegexKitLite.html
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta http-equiv="Content-Language" content="EN-US"> <meta name = "format-detection" content = "telephone=no"> <style type="text/css"> body { font: 12px "lucida grande", geneva, helvetica, arial, sans-serif; color: #000; background-color: #FFF; } h1 { margin-top: 1.0em; margin-bottom: 0.8334em; font-size: 2.5000em; } h2 { margin-top: 2.5em; margin-bottom: 2.0000ex; font-size: 2.0000em; border-bottom: 1px solid #5088C5; color: #3C4C6C; clear: both; } h3 { margin-top: 2.0em; margin-bottom: 0.5000em; font-size: 1.5834em; } h4 { margin-top: 2.0em; margin-bottom: 0.5000em; font-size: 1.2500em; } h5 { margin-top: 1.5em; margin-bottom: 0.5000em; font-size: 1.0834em; padding: 0px; } A:link, a:link .code { text-decoration: none; color: #36C; } A:link:hover, a:link:hover .code { text-decoration: underline; color: #36C; } A:active, a:active .code { text-decoration: underline; color: #36C; } A[name]:active { text-decoration: none; color: #000; } A:visited, a:visited .code { text-decoration: none; color: #036; } A:visited:hover, a:visited:hover .code { text-decoration: underline; color: #036; } .spacer { height: 0px; width: 100%; margin-top: 0.5em; margin-bottom: 0.5em; border-top: 1px solid #fafafa; border-bottom: 1px solid #fdfdfd; } .indent { margin-left: 4ex; } .bar { height: 0px; width: 100%; margin-top: 0.5em; margin-bottom: 0.5em; border-bottom: 1px solid #a1a5a9; } .hide { display: none; } .RED { border: 2px solid #f00; padding: 1ex; -webkit-border-radius: 5px; -webkit-box-shadow: 3px 3px 4px #900; -moz-border-radius: 5px; -moz-box-shadow: 3px 3px 4px #900; border-radius: 5px; box-shadow: 3px 3px 4px #900; white-space: pre-wrap; } .XXX { border: 2px solid red; padding: 2px; margin: 0.75em 0px; } .XXX { border-color: rgba(255,0,0,0.8); -webkit-border-radius: 6px; /*text-shadow: 2px 2px 2px rgba(68,0,0,0.4);*/ -moz-border-radius: 6px; border-radius: 6px; } .DoNot { font-weight: bold; font-style: italic; text-decoration: underline; } .nobr { white-space: nowrap; white-space: pre-wrap !important; } .hardNobr { white-space: nowrap; } .noBold { font-weight: normal !important; } .noUnderline { text-decoration: none !important; } img.noBorder { border: 0px solid #000; } .noSelect { -moz-user-select: none; -webkit-user-select: none; cursor: default; } .canSelect { -moz-user-select: text; -webkit-user-select: text; cursor: auto; } .marginTopSpacer { margin-top: 1em !important; } .marginBottomSpacer { margin-bottom: 1em !important; } .marginLeftSpacer { margin-left: 1ex !important; } .marginRightSpacer { margin-right: 1ex !important; } .marginSpacer { margin: 1em 1ex !important; } .floatRight { float: right; } .floatRightPadder { text-align: right; clear: both; height: 0px; } .floatLeft { float: left; } .floatLeftPadder { text-align: left; clear: both; height: 0px; } .clearLeft { clear: left; } .clearRight { clear: right; } .clearBoth { clear: both; } .rightHack { text-align: right; text-align: -webkit-right; text-align: -moz-right; } .centerHack { text-align: center; text-align: -webkit-center; text-align: -moz-center; } .leftHack { text-align: left; text-align: -webkit-left; text-align: -moz-left; } .submenuArrow { font-size: 0.75em; } .table { display: table; } .table > .row { display: table-row; } .table > .row > .cell { display: table-cell; } .table > .row > .cell.metacharacters { width: 50%; } .table > .row > .cell.operators { width: 50%; } .table.perfNumbers > .row > .cell { padding-right: 1.5em; } ul.highlights { margin-left: 4.0ex; padding-left: 1ex; } ul.highlights li { margin-top: 0.5em; } ul.square { list-style-type: square; } ul.square > li > *:first-child { margin-top: 0px; } ul.square > li > .box.sourcecode:last-child { margin-bottom: 1em; } ul.compare { margin: 0px; padding: 0px; } ul.compare > li { margin: 0px 0px 0px 2ex; } ul.overview { margin-left: 9.5ex; list-style-type: none; } ul.overview li { margin-top: 0em; } ul.seealso { margin: 0px; padding: 0px; list-style-type: none; } ul.seealso > li { margin: 0px 0px 0px 6.25ex; } /* table styles */ table + table { margin-top: 1em; } table + .box { margin-top: 1em; } /* The standard table style */ table.standard { border-spacing: 0px; -moz-border-radius: 0.5ex; -webkit-border-radius: 0.5ex; border-radius: 0.5ex; } table.standard caption { margin-bottom: 0.5em; text-align: left; } table.standard caption > .identifier { font-weight: bold; margin-right: 1.5ex; } table.standard th { padding: 0.3334em 1ex; text-align: left; border-bottom: 1px solid #919699; border-right: 1px solid #919699; background: #E2E2E2; } table.standard td { vertical-align: top; padding: 1ex; border-bottom: 1px solid #919699; border-right: 1px solid #919699; } table.standard tr:first-child > *:first-child, table.regexSyntax tr:first-child > *:first-child { -moz-border-radius-topleft: 0.5ex; -webkit-border-top-left-radius: 0.5ex; border-top-left-radius: 0.5ex; } table.standard tr:first-child > *:last-child, table.regexSyntax tr:first-child > *:last-child { -moz-border-radius-topright: 0.5ex; -webkit-border-top-right-radius: 0.5ex; border-top-right-radius: 0.5ex; } table.standard tr:last-child > *:first-child, table.regexSyntax tr:last-child > *:first-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; } table.standard tr:last-child > *:last-child, table.regexSyntax tr:last-child > *:last-child { -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } table.regexSyntax { border-spacing: 0px; /* border-top: 1px solid #919699; border-left: 1px solid #919699; */ margin-left: 1.5ex; margin-right: 1.5ex; -moz-border-radius: 0.5ex; -webkit-border-radius: 0.5ex; border-radius: 0.5ex; } table.regexSyntax caption { margin-bottom: 0.5em; text-align: left; } table.regexSyntax caption > .identifier { font-weight: bold; margin-right: 1.5ex; } table.regexSyntax th { padding: 0.3334em 1ex; text-align: left; border-bottom: 1px solid #919699; border-right: 1px solid #919699; background: #E2E2E2; -webkit-background-origin: border; } table.regexSyntax td { padding-left: 0.75ex; padding-right: 0.75ex; padding-top: 0.1875em; padding-bottom: 0.1875em; border-bottom: 1px solid #919699; border-right: 1px solid #919699; -webkit-background-origin: border; } table.regexSyntax i + .regex { margin-left: 0.3125ex; } .redOutline { outline: 1px solid rgba(255,0,0,0.25); } .greenOutline { outline: 1px solid rgba(0,255,0,0.25); } .blueOutline { outline: 1px solid rgba(0,0,255,0.25); } .transitionColor { -webkit-transition: color 0.33s cubic-bezier(0.43, 0, 1.0, 0.75), text-shadow 0.33s cubic-bezier(0.43, 0, 1.0, 0.75); } .transitionRed { color: #f00 !important; } .transitionGreen { color: #0f0 !important; text-shadow: 1px 1px 3px rgba(0,255,0,0.4); } .transitionBlue { color: #00f !important; } .pulseOutlineRed { -moz-box-shadow: 0px 0px 1.85ex rgba(255,0,0,1.0) !important; -webkit-box-shadow: 0px 0px 1.85ex rgba(255,0,0,1.0) !important; } .pulseOutline { -webkit-transition: -webkit-box-shadow 0.5s ease-out; } .copyToClipboardHUDAnimate { -webkit-transition: top 0.25s ease-in-out, width 0.45s ease-in-out, left 0.45s ease-in-out; } .copyToClipboardHUD { -moz-user-select: none; -webkit-user-select: none; cursor: default; } .copyToClipboardHUD > .top { padding-top: 0px; padding-bottom: 0px; margin-left: 35px; margin-right: 35px; background: rgba(8,8,8,0.75); -webkit-border-bottom-left-radius: 10px; -webkit-border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; -moz-border-radius-bottomleft: 10px; -moz-border-radius-bottomright: 10px; border: 2px solid rgb(207,207,207); border-top: 0px solid transparent; -moz-box-shadow: 0px 0px 10px rgba(0,0,0,0.9); color: #fff; text-shadow: 0px 0px 1px rgba(0,0,0,0.75); -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,0.9); box-shadow: 0px 0px 10px rgba(0,0,0,0.9); z-index: 100; text-align: center; -webkit-background-origin: border !important; -moz-background-origin: border; } .copyToClipboardHUD > .top > .padding { padding-top: 0.25em; padding-bottom: 0.5em; } .copyToClipboardHUD > .top > .padding > .copiedAs { white-space: nowrap; margin-left: 3ex; margin-right: 3ex; font-weight: bold; } .copyToClipboardHUD .copyToClipboardHUDRegex { margin-top: 0.75em; margin-left: 4ex; margin-right: 4ex; color: #fff; text-shadow: 0px 0px 2px rgba(0,0,0,0.75); overflow: hidden; text-overflow: ellipsis; -webkit-background-origin: border; -moz-background-origin: border; } .copyToClipboardHUD.example > .top { margin-right: 13px; margin-left: 13px; } .copyToClipboardDisplayExample { margin: 1em 0px; } .copyToClipboardDisplayExample .cell { vertical-align: top; } div.clipboardExamples#topContainer { margin-bottom: 0.5em; } div#clip { overflow: hidden; } .faq { margin-left: 6ex; margin-right: 6ex; } .faq > .qa { margin-bottom: 1.5em; } .faq > .qa > .q { font-weight: bold; } .faq > .qa > .a { margin: 0.25em 1.75ex; } .faq > .qa > .q > p:first-child, .faq > .qa > .a > p:first-child { margin-top: 0px; } .bottomBevel { border-bottom: 1px solid #e0e0e0; border-bottom: 1px solid rgba(0,0,0,0.1); -webkit-background-origin: border; -moz-background-origin: border; } .topBevel { border-top: 1px solid #fdfdfd; border-top: 1px solid rgba(255,255,255,0.75); -webkit-background-origin: border; -moz-background-origin: border; } .leftBevel { border-left: 1px solid #fdfdfd; border-left: 1px solid rgba(255,255,255,0.75); -webkit-background-origin: border; -moz-background-origin: border; } .rightBevel { border-right: 1px solid #e0e0e0; border-right: 1px solid rgba(0,0,0,0.1); -webkit-background-origin: border; -moz-background-origin: border; } .box { margin: 0.5em 3ex; padding: 0.5em 1.75ex; text-align: left; vertical-align: top; border: 1px solid #a1a5a9; background-color: #f7f7f7; } .box + .box { margin-top: 1em; } .box p { margin: 0px 0px; } .box p + p { margin-top: 1em; } .box.important { border-color: #111; background-color: #e8e8e8; } .box.warning { border-color: #000; background-color: #fff; } .box.caution { border-color: #000; background-color: #fcfcfc; border-width: 2px; } .box.tip, .box.small { border-color: #c3c3c3; background-color: #e9e9e9; padding: 0.25em 1.0ex; } .box.tip { display: table; -webkit-border-radius: 1.0em; -moz-border-radius: 1.0em; border-radius: 1.0em; } .box.small { float: left; clear: both; margin: 0.5ex; -webkit-border-radius: 0.85em; -moz-border-radius: 0.85em; border-radius: 0.85em; } .box.note, .box.important, .box.warning, .box.caution { -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; color: #000; } .box .message p:first-child { margin-top: 0px; } .box .message p:last-child { margin-bottom: 0px; } .box .label { padding-right: 1.5ex; font-weight: bold; vertical-align: middle; } .box.tip .label { padding-right: 1.0ex; } .box.small .label { padding-right: 0.5ex; } .box.sourcecode, .box.shell, .box.quote { margin-left: 0px; margin-right: 0px; padding: 1.0em 2ex; -webkit-border-radius: 0.5ex; -moz-border-radius: 0.5ex; border-radius: 0.5ex; } .box.sourcecode, .box.shell, .shellFont { font: 0.9167em monaco, "Lucida Console", courier, monospace; } .box.sourcecode, .box.shell { white-space: pre; white-space: pre-wrap !important; } .box.sourcecode { border: 1px solid #c7cfd5; background-color: #f1f5f9; } /*.box.sourcecode .comment { font-weight: bold; font-size: 0.9167em; }*/ .box.shell { border: 1px solid #bddbc5; background-color: #eafff5; } .box.quote { border: 1px solid #c7cfd5; background-color: #f0f0f0; } .box.shell .userInput { font-weight: bold; font-size: 0.9167em; } .box.shell .userInput .return { font-weight: normal; font-size: 1.1000em; margin-left: 0.5ex; } .box.hasRows { display: table; padding: 0px; background-color: white; border-left: 1px solid #919699; border-top: 1px solid #919699; } .box.hasRows > .row { display: table-row; } .box.hasRows > .row > .cell { display: table-cell; padding: 1ex; border-bottom: 1px solid #919699; border-right: 0.834em solid #919699; } .box.hasRows > .row > .cell.lastCell { border-right: none; } .box.hasRows > .row.lastRow > .cell { border-bottom: none; } /* zebra rows are tagged even/odd. Scripts/common.js:fixupBoxRows() will automatically populate and/or correct any even/odd tags */ .box.hasRows.zebraRows > .row.odd { background-color: #F0F5F9; } .box.hasRows > .row.headerRow { background-color: #E2E2E2; } .box.hasRows > .row.headerRow .cell { padding-top: 0.3334em; padding-bottom: 0.3334em; } .box.frameworkSpecs .row.regexKitVersion .releaseNotes, .box.classSpecs .row.regexKitVersion .releaseNotes { margin-left: 2ex; } .box.classSpecs > .row > .cell.left { font-weight: bold; border-right: none; } .box.classSpecs > .row > ul.cell.right { list-style-type: none; } .box.classSpecs { -webkit-border-radius: 0.5ex; -moz-border-radius: 0.5ex; border-radius: 0.5ex; } .box.hasRows > .row:first-child { -moz-border-radius-topleft: 0.5ex; -webkit-border-top-left-radius: 0.5ex; border-top-left-radius: 0.5ex; -moz-border-radius-topright: 0.5ex; -webkit-border-top-right-radius: 0.5ex; border-top-right-radius: 0.5ex; } .box.hasRows > .row:last-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } .box.hasRows > .row:first-child > *:first-child { -moz-border-radius-topleft: 0.5ex; -webkit-border-top-left-radius: 0.5ex; border-top-left-radius: 0.5ex; } .box.hasRows > .row:first-child > *:last-child { -moz-border-radius-topright: 0.5ex; -webkit-border-top-right-radius: 0.5ex; border-top-right-radius: 0.5ex; } .box.hasRows > .row:last-child > *:first-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; } .box.hasRows > .row:last-child > *:last-child { -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } .box .highlight { padding-left: 0.175ex; padding-right:0.175ex; padding-bottom: 0.1em; margin-right:0.175ex; margin-left:0.175ex; border: 1px solid #888; -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; } .box .metainfo { display: table; font: 12px "lucida grande", geneva, helvetica, arial, sans-serif; white-space: normal; padding: 0.125em 0.75ex; border: 1px solid #ccc; border-color: rgba(0,0,0,0.15); background-color: rgba(0,0,0,0.05); -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; float: right; -webkit-user-select: none; -moz-user-select: none; cursor: default; -webkit-background-origin: border; -moz-background-origin: border; } .box .metainfo .info { padding-left: 1.0ex; } .box .metainfo > .entry { display: table-row; } .box .metainfo > .entry > .item { display: table-cell; } .box .metainfo > .entry > .meta { font-style: italic; } .box .metainfo .filename > .info, .box .metainfo .taggedAs > .info { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .box .metainfo .continues.above > .info { padding-left: 0px; font: italic 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .box .metainfo .description > .info { padding-left: 0px; font: italic 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .box.titled { margin: 0px; padding: 0px; border: 0px solid transparent; background-color: transparent; -webkit-border-radius: 0.625em; -moz-border-radius: 0.625em; border-radius: 0.625em; } .box.titled > .title { padding: 0.25em 2ex; line-height: 1.5em; font-size: 13px; font-weight: bold; -webkit-border-top-left-radius: 0.625em; -webkit-border-top-right-radius: 0.625em; border-top-left-radius: 0.625em; border-top-right-radius: 0.625em; -moz-border-radius-topleft: 0.625em; -moz-border-radius-topright: 0.625em; -webkit-user-select: none; -moz-user-select: none; cursor: default; -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .box.titled > .contents { padding: 0.5em 2ex; line-height: 1.5em; font-size: 11px; -webkit-border-bottom-left-radius: 0.625em; -webkit-border-bottom-right-radius: 0.625em; border-bottom-left-radius: 0.625em; border-bottom-right-radius: 0.625em; -moz-border-radius-bottomleft: 0.625em; -moz-border-radius-bottomright: 0.625em; border: 1px solid #e5e5e5; border-top: 0px !important; background: #f5f5f5; color: #555; -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .box.titled > .title.blueGrey { background: #7a88a1; background: -webkit-gradient(linear, left top, left bottom, from(rgba(162,170,186,1.0)), to(rgba(114,131,157,1.0))); background: -moz-linear-gradient(top, rgba(162,170,186,1.0), rgba(114,131,157,1.0)); color: #fff; text-shadow: 0px 1px 2px #333; border-top: 1px solid rgba(255,255,255,0.125); border-left: 1px solid rgba(0,0,0,0.025); border-right: 1px solid rgba(0,0,0,0.025); border-bottom: 1px solid rgba(0,0,0,0.025); -webkit-background-origin: border !important; } .box.titled > .title.dkRed { background: #7c2f26; background: -webkit-gradient(linear, left top, left bottom, from(rgba(140,96,91,1.0)), color-stop(0.0125, rgba(145,100,94,1)), color-stop(0.66,rgba(117,43,35,1.0)), to(rgba(115,42,34,1.0))); color: #fff; text-shadow: 0px 1px 2px #222; } .box.titled > .title.metal { background: #d8d8d8; background: -webkit-gradient(linear, left top, left bottom, from(rgba(223,223,223,1.0)), to(rgba(206,206,206,1.0)) ); color: #666; text-shadow: 1px 1px 0px #e9e9e9; text-shadow: 1px 1px 0px rgba(255,255,255,0.4); border-top: 1px solid rgba(255,255,255,0.65); border-left: 1px solid rgba(0,0,0,0.04); border-right: 1px solid rgba(0,0,0,0.04); border-bottom: 1px solid #afafaf; } .box.titled > .contents.metal { background: #ccc; background: -webkit-gradient(linear, left top, left bottom, from(rgba(204,204,204,1.0)), to(rgba(190,190,190,1.0))); color: #fff; text-shadow: 0px 1px 2px #333; border-top: 1px solid #e0e0e0 !important; border-left: 1px solid rgba(0,0,0,0.04); border-right: 1px solid rgba(0,0,0,0.04); border-bottom: 1px solid #aaa; } .box.titled > .title.alum { background: #eee; color: #333; border: 1px solid #d3d3d3; border-bottom: 1px solid #bcbcbc !important; } .box.titled > .contents.alum { background: #fafafa; color: #555; border-top-width: 0px; border-left: 1px solid #e1e1e1; border-right: 1px solid #e1e1e1; border-bottom: 1px solid #c4c4c4; } .box.titled > .contents.alum2 { color: #222; background: #f8f8f8; border-top: 1px solid #fcfcfc !important; border-left: 1px solid #e1e1e1; border-right: 1px solid #e1e1e1; border-bottom: 1px solid #c4c4c4; } .box.titled > .contents.whiteToLight { background: -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,1.0)), to(rgba(241,241,241,1.0))); border: 1px solid #cecece; } .box.titled > .contents.whiteToLight2 { background: -webkit-gradient(linear, left top, left bottom, from(rgba(250,250,250,1.0)), to(rgba(241,241,241,1.0))); border: 1px solid #cecece; } .box.titled.copyToClipboard.preferences { float: right; margin: 1em 3ex; -moz-user-select: none; -webkit-user-select: none; max-width: 33%; min-width: 350px; cursor: default; } .box.titled.copyToClipboard.preferences .contents .inset .code { color: #222; } .box.titled.copyToClipboard.preferences .contents .inset .prefsUI { margin: 3px; } .box.titled.copyToClipboard.preferences .contents .inset .prefsUI .copyRegexPrefsRow > .UIlabel { text-align: right; } .box.titled.copyToClipboard.preferences .contents .inset .prefsUI .copyRegexPrefsRow > .UIcontrol, .box.titled.copyToClipboard.preferences .contents .inset .prefsUI .copyRegexPrefsRow > .UIcontrolLabel { text-align: left; } .box.titled.copyToClipboard.preferences .contents .inset .prefsUI input { margin: 0px; } .box.titled.regexEscapeTool.UIpane { width: 45%; max-width: 75%; min-width: 350px; float: right; margin: 2em 3ex; } .box.titled.regexEscapeTool.UIpane .contents .contain { position: relative; padding-right: 4px; } .box.titled.regexEscapeTool.UIpane textarea.regex { width: 100%; resize: none; -webkit-border-radius: 3px; border-color: #c4c4c4; border-top-color: #aaa; padding: 1px; font-size: 1em; } .box.titled.regexEscapeTool.UIpane .inset { font-size: 12px; } .box.titled.regexEscapeTool.UIpane .inset #interactiveEscapedOutput { min-height: 5em; max-height: 12em; margin: 0.125em 1.0ex; white-space: pre-wrap; overflow: auto; text-shadow: 1px 1px 1px rgba(0,0,0,0.2); color: #333; } .safariOnly { display: none; } .enhancedCopyOnly { display: none; } .disabledPref, .disabledPref > *, .disabledPref > * > *, .disabledPref > * > * > * { color: #808080 !important; } .copyToClipboard.preferences .hidden { opacity: 0; } .copyToClipboard.preferences .marginAndOpacityTransition { -webkit-transition: margin-bottom 0.25s ease-out, opacity 0.15s ease-out; -webkit-transition-delay: 1s; } .copyToClipboard.preferences .marginAndOpacityTransition.hidden { -webkit-transition: margin-bottom 0.25s ease-in-out, opacity 0.15s ease-out; -webkit-transition-delay: 1s;} .UIcontrolLabel { cursor: default; } .clipboardExamples .UIlabel { margin: 0.5em 0px 0.25em 0.25ex } .copyToClipboard.preferences .contents .UItopTitleSpacer { margin-top: 6px; } .box.titled .contents .UIcontentSpacer { margin: 6px 0px 4px 0px; } .prefWarnings .prefWarningsSpacer { margin: 0.25em 1ex; } .prefWarnings .prefWarningsTable + .prefWarningsTable { margin-top: 0.5em; } .prefWarnings .prefWarningsTable > .row > .cell.label { text-align: right; padding-right: 1.5ex; } .escapedUnicodeInNSStringLiterals { display: inline; } hr.beveled { margin: 0px; border: 0px solid transparent; border-top: 1px solid rgba(0,0,0,0.1); border-bottom: 1px solid rgba(255,255,255,0.75); -webkit-background-origin: border; -moz-background-origin: border; } .copyToClipboard.preferences hr.beveled { margin: 0.125em 0px; } .insetOuter { -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; border-top: 1px solid rgba(0,0,0,0.25); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .insetMiddle { -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; border-top: 1px solid rgba(0,0,0,0.15); border-left: 1px solid rgba(0,0,0,0.14); border-right: 1px solid rgba(0,0,0,0.12); border-bottom: 1px solid rgba(0,0,0,0.10); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .inset { -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; border-top: 1px solid rgba(0,0,0,0.05); border-left: 1px solid rgba(0,0,0,0.04); border-right: 1px solid rgba(0,0,0,0.03); border-bottom: 1px solid rgba(0,0,0,0.02); background: #f8f8f8; background: rgba(0,0,0,0.03); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .figure .caption { margin-bottom: 0.5em; margin-top: 0.5em; } .figure .caption .number { font-weight: bold; margin-right: 1.25ex; white-space: nowrap; } .signature { margin-top: 1em; margin-bottom: 0.75em; font: 0.9166em monaco, "Lucida Console", courier, monospace; } .signature .code { font-size: 1em !important; } .block { margin: 2.5em 0px 0px 0px; padding: 2.5em 0px 0px 0px; } .block .header + p { margin-top: 0px; } .block.dtrace.small > .signature { margin-left: 2ex; } .section { margin-top: 1em; margin-bottom: 1em; padding: 0px; } .section > .header { font-weight: bold; font-size: 1.0834em; margin-bottom: 0.1667em; } .section p { margin-top: 0.5em; margin-bottom: 0.5em; } .section.discussion p { margin-top: 1em; margin-bottom: 1em; } .section.summary { margin-top: 0.75em; margin-bottom: 0.75em; } .section.name { font-size: 1.5833em; font-weight: bold; margin-top: 0px; margin-bottom: 0px; } .section.parameters { margin-top: 1.5em; } .section.block.parameters { margin-top: 0.5em; } .section.seealso ul { list-style-type: none; margin: 0px; padding: 0px; } .section.seealso li { margin: 0px; } .section.seealso ul.offset > li, ul.seealso > li { margin: 0px 0px 0px 6.25ex; } .section.parameters ul { list-style-type: none; margin: 0px 0px 0px 2ex; padding: 0px; } .section.parameters li { margin: 0px; } .section.parameters li .name { font-style: italic; } .section.parameters li .text { margin-top: 0.0834em; margin-left: 4ex; margin-bottom: 0.5em; } .block.typedef { margin-top: 5em; margin-bottom: 0px; padding-top: 0px; } .block.typedef > .section.name { margin-bottom: 0.5em; } .block.typedef > .section.summary { margin-top: 1em; } .block.typedef > .section.type { margin-bottom: 0.75em; font: 0.9166em monaco, "Lucida Console", courier, monospace; } .block.constants { margin-top: 1.5em; padding-top: 0px; } .block.constants > .section.summary { margin-top: 1em; margin-bottom: 1.25em; } .block.constants > .section.declaration .code { font-size: 1em; color: #000; } .block > .section.declaration { font: 0.9167em monaco, "Lucida Console", courier, monospace; color: #000; margin-top: 0px; margin-bottom: 0px; } .block > .section.declaration > .enum > .identifier { padding-left: 4ex; } .block > .section.declaration > .enum > .equals { padding-left: 2ex; padding-right: 2ex; } .block > .section.constants { margin-top: 1.5em; } .block > .section.constants > .section.summary { margin-top: 1em; margin-bottom: 1.25em; } .block > .section.constants > .section.header { margin-bottom: 0.25em; } .block > .section.constants > .section.declaration .name.code { color: #000; } .block > .section.constants > .constant { margin-top: 0.5em; margin-bottom: 0.5em; } .block > .section.constants > .constant > .identifier { font: 0.9167em monaco, "Lucida Console", courier, monospace; /*color: #666;*/ } .block > .section.constants > .constant > .text { margin-left: 2ex; } .block > .section.constants > .constant > .text > p { margin-top: 0px; margin-bottom: 0px; } .block > .section.constants > .constant > .text > p + p { margin-top: 1em; } h1.reference { margin-top: 2.5em; } h3 .code { color: black; } h4 .code { color: black; } .overview { margin-bottom: 1em; } .overview .masthead { font-size: 2.0000em; font-weight: bold; margin-top: 2.5em; margin-bottom: 2.0ex; border-bottom: 1px solid black; } .overview .header { font-size: 1.5833em; font-weight: bold; margin-top: 1.5em; margin-bottom: 0.5em; } .overview .section { font-size: 1.2500em; font-weight: bold; margin-top: 2.0em; margin-bottom: 0.5em; } .overview .seealso > ul { margin: 0px; padding: 0px; list-style-type: none; } .overview .seealso > ul > li { margin-left: 6.25ex; } .tasks { margin-bottom: 1em; } .tasks > .header { font-size: /*1.5833em;*/ 1.4166em; font-weight: bold; margin-top: 1.5em; margin-bottom: 0.5em; } .tasks .header .code { font: bold 1em "lucida grande", geneva, helvetica, arial, sans-serif; } .tasks > ul { margin: 0px; padding: 0px; list-style-type: none; } .tasks > ul > li { margin-left: 6.25ex; } .protocols { margin-bottom: 1em; } .protocols > .header { margin-bottom: 0.75ex; } .protocols > ul { margin: 0px; padding: 0px; list-style-type: none; } .protocols > ul > li { margin-left: 6.25ex; } .chrono { margin-left: 1.5ex; margin-bottom: 2em; padding-right: 4ex; } .chrono ul { margin-left: 4.0ex; padding-left: 1ex; list-style-type: square; } .chrono ul li { margin-top: 0.5em; } .chrono ul.square > li > *:first-child { margin-top: 0px; } .chrono ul.square > li > *:last-child { margin-bottom: 0px; } .chrono ul.square > li > * { margin-top: 0.5em; margin-bottom: 0.5em; } .chrono ul.square > li > .box.sourcecode { margin-bottom: 0.85em; } .chrono > .entry { margin-left: 2ex; margin-bottom: 1.75em; padding-right: 2ex; } .chrono > .entry > .banner { margin-left: -1.25ex; font-size: 1.0834em; } .chrono > .entry > .banner > .bannerItemSpacer { margin-right: 1.25ex; margin-left: 1.25ex; } .chrono > .entry > .bannerSpacer { margin-left: -2.0ex; border-bottom: 1px solid #d8d8d8; margin-top: 0.25em; margin-bottom: 0.25em; width: 95% } .chrono > .entry > .content { margin-top: 0.5em; } .chrono > .entry > .content > p:first-child { margin-top: 0px; margin-bottom: 0px; } .chrono > .entry > .content .standout { margin-top: 1.75em; /*margin-bottom: 0.5000em;*/ font-size: 1.0875em; font-weight: bold; } .quotation { margin: 1em 6.25ex 1em 6.25ex; } .quotation .quote { font-style: italic; padding-right: 2.5ex; } .quotation .attribution { text-align: right; font-variant: small-caps; } .quotation .attribution:before { content:"\2014"; } .sourceLicense { margin: 2em 4ex; max-width: 5.75in; text-align: justify; } .sourceLicense ul { list-style-type: disk; } .sourceLicense li { margin-bottom: 0.75em; } .sourceLicense .disclaimer { font-family: courier, monospace; } .pop-up_menu-selection, .pop-up_menu-name, .menu-selection, .checkbox-name, .tab-name, .button-name, .icon-button-name { font: 0.9167em monaco, "Lucida Console", courier, monospace !important; white-space: nowrap !important; } .deprecated { color: #f00; } .quotedText { font: 0.9167em monaco, "Lucida Console", courier, monospace; } .code { font: 0.9167em monaco, "Lucida Console", courier, monospace; /*color: #666;*/ } .parameterChoice { font-style: italic; font-size: 0.9167em; white-space: nowrap; margin-right: 0.2em; } .consoleText { font: 0.8334em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .regex { font: 0.8334em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .regex b { font: bold 1.1000em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .regex-textual { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .regex-def { font: italic 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .regexMatch { font: 0.8334em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .argument { font-style: italic; white-space: nowrap; } .section-link { font-style: italic; white-space: nowrap; white-space: pre-wrap !important; } .cpp_flag { font-weight: bold; white-space: nowrap; } .code .cpp_flag { font-weight: normal; font-style: italic; white-space: nowrap; } .cpp_definition { font-weight: bold; color: #f00; } .header_file { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; /*color: #666;*/ } .frameworkabstract { font-size: 1.0000em; } .file { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; /*color: #666;*/ } .build-phase { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .dialog-option { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .xcode-group { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .xcode-setting { font-weight: bold; white-space: nowrap; } .xcode-target { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .window-name { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .context-menu { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .xcode-button { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; } .user-supplied { font-style: italic; white-space: nowrap; } .new-term { font-weight: bold; white-space: nowrap; } .exponent { font-size: 0.7500em; vertical-align: super; } .unicodeCharName { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; /*color: #666;*/ } .unicodeProperty { font: 0.9167em monaco, "Lucida Console", courier, monospace; white-space: nowrap; /*color: #666;*/ } .standardFont { font: 1em "lucida grande", geneva, helvetica, arial, sans-serif; } .rkl { white-space: nowrap; } @media screen { .printOnly { display: none; } .softNobr { white-space: nowrap; } .syntax > .specification .optional { -moz-box-shadow: 2px 3px 5px #888; -webkit-box-shadow: 2px 3px 5px #888; box-shadow: 2px 3px 5px #888; } .XXX { -moz-box-shadow: 8px 8px 10px #666; -webkit-box-shadow: 3px 3px 8px #666; box-shadow: 3px 3px 8px #666; } .box { -moz-box-shadow: 3px 3px 4px #999; -webkit-box-shadow: 3px 3px 4px #999; box-shadow: 3px 3px 4px #999; } .box.caution { -moz-box-shadow: 0px 0px 5px #000; -webkit-box-shadow: 0px 0px 5px #000; box-shadow: 0px 0px 5px #000; } .box .metainfo { -moz-box-shadow: 2px 2px 3px #999; -webkit-box-shadow: 2px 2px 3px #999; box-shadow: 2px 2px 3px #999; background: rgba(0,0,0,0.05); background: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0.0)), to(rgba(0,0,0,0.1))); background: -moz-linear-gradient(top, rgba(0,0,0,0.0), rgba(0,0,0,0.1)); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .box .metainfo.bottom { margin-top: -1.6666em; } .box.titled.UIpane { -moz-box-shadow: 0px 5px 10px #aaa; -webkit-box-shadow: 0px 5px 10px #aaa; box-shadow: 0px 5px 10px #aaa; } .box.titled.regexEscapeTool.UIpane textarea { -moz-box-shadow: 0px 0px 2px #c2c2c2; -webkit-box-shadow: 0px 0px 2px #c2c2c2; box-shadow: 0px 0px 2px #c2c2c2; } table.standard { -moz-box-shadow: 3px 3px 4px #999; -webkit-box-shadow: 3px 3px 4px #999; box-shadow: 3px 3px 4px #999; } table.standard caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; box-shadow: 0px 0px 0px #000; } table.regexSyntax { -moz-box-shadow: 3px 3px 4px #999; -webkit-box-shadow: 3px 3px 4px #999; box-shadow: 3px 3px 4px #999; } table.regexSyntax caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; box-shadow: 0px 0px 0px #000; } table.standard th, table.regexSyntax th { text-shadow: rgba(0,0,0,0.33) 0px -1px 0px; background: #93A5BB; background: -webkit-gradient(linear, left top, left bottom, from(rgba(190,199,214,1.0)), color-stop(0.5, rgba(155,172,191,1.0)), color-stop(0.5, rgba(147,166,187,1.0)), to(rgba(128,150,176,1.0))); background: -moz-linear-gradient(top, rgba(190,199,214,1.0), rgba(155,172,191,1.0) 50%, rgba(147,166,187,1.0) 50%, rgba(128,150,176,1.0)); color: #fff; border-top: 1px solid #b8b8b8; border-top: 1px solid rgba(255,255,255,0.2); border-bottom: 1px solid #b8b8b8; border-bottom: 1px solid rgba(255,255,255,0.25); border-left: 1px solid #e0e0e0; border-left: 1px solid rgba(255,255,255,0.15); border-right: 1px solid #c0c0c0; border-right: 1px solid rgba(0,0,0,0.05); -webkit-background-origin: border !important; -moz-background-origin: border !important; background-origin: border !important; } table.standard tr > td:first-child, table.regexSyntax tr > td:first-child { border-left: 1px solid #9BB3CD; } table.standard td { border-bottom: 1px solid #9BB3CD; border-right: 1px solid #9BB3CD; } table.regexSyntax td { border-bottom: 1px solid #9BB3CD; border-right: 1px solid #9BB3CD; } table.regexSyntax .highlight { padding: 0.0em 0.625ex 0.1em 0.625ex; border: 1px solid #ddd; -webkit-border-radius: 0.5em; -moz-border-radius: 0.5em; border-radius: 0.5em; } table.regexSyntax .highlight { border: 1px solid rgba(0,0,0,0.075); background: rgba(0,0,0,0.05); background: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0.0)), to(rgba(0,0,0,0.1))); background: -moz-linear-gradient(top, rgba(0,0,0,0.0), rgba(0,0,0,0.1)); -moz-box-shadow: 0px 0px 2px rgba(0,0,0,0.375); -webkit-box-shadow: 0px 0px 1px rgba(0,0,0,0.375); box-shadow: 0px 0px 1px rgba(0,0,0,0.375); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } .box .highlight { border: 1px solid rgba(0,0,0,0.075); background: rgba(0,0,0,0.05); background: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0.0)), to(rgba(0,0,0,0.1))); background: -moz-linear-gradient(top, rgba(0,0,0,0.0), rgba(0,0,0,0.1)); -moz-box-shadow: 0px 0px 2px rgba(0,0,0,0.375); -webkit-box-shadow: 0px 0px 1px rgba(0,0,0,0.375); box-shadow: 0px 0px 1px rgba(0,0,0,0.375); -webkit-background-origin: border; -moz-background-origin: border; background-origin: border; } table.slate:not(.clipboardExamples) { -moz-box-shadow: 2px 2px 3px #999; -webkit-box-shadow: 2px 2px 3px #999; box-shadow: 2px 2px 3px #999; } div#shadow { -moz-box-shadow: 0px 2px 3px #bbb; -webkit-box-shadow: 0px 1px 2px #ccc; box-shadow: 0px 1px 2px #ccc; } .reference > h3.InstanceMethods { margin-top: 2.5em; margin-bottom: 2ex; font-size: 2em; border-bottom: 1px solid black; clear: both; } .reference > h3 { margin: 2em 0px 0.5em 0px; font-size: 1.4166em; } .reference > h4 { margin: 2em 0px 0.5em 0px; font-size: 1.25em; } table.slate { border-spacing: 0px; margin: 0px 0px 0.5em 0px; background: #fcfcfc; } table.slate caption { margin-bottom: 0.5em; text-align: left; } table.slate caption > .identifier { font-weight: bold; margin-right: 1.5ex; } table.slate th { white-space: nowrap; font-size: 0.9167em; padding: 0.1em 0.75ex; text-align: left; background: #ccc; background: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#bbb)); background: -moz-linear-gradient(top, #dbdbdb, #bbb); color: #202020; text-shadow: 1px 1px 1px #cfcfcf; text-shadow: 0px 1px 1px rgba(255,255,255,0.95); border-bottom: 1px solid #b8b8b8; border-top: 1px solid #f3f3f3; border-left: 1px solid #e0e0e0; border-left: 1px solid rgba(255,255,255,0.35); border-right: 1px solid #c0c0c0; border-right: 1px solid rgba(0,0,0,0.05); -webkit-background-origin: border !important; -moz-background-origin: border !important; background-origin: border !important; } table.slate, table.slate tr, table.slate th, table.slate td, table.slate tbody { -webkit-background-origin: border !important; -moz-background-origin: border !important; background-origin: border !important; } table.slate td { padding: 0.1em 1.0ex; color: #202020; text-shadow: 0px 1px 0px #fbfbfb; text-shadow: 0px 1px 0px rgba(255,255,255,0.75); background: #f5f5f5; background: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#ebebeb)); background: -moz-linear-gradient(top, #fafafa, #ebebeb); border-top: 1px solid #fbfbfb; border-top: 1px solid rgba(255,255,255,0.25); border-bottom: 1px solid #e8e8e8; border-bottom: 1px solid rgba(0,0,0,0.015); border-left: 1px solid #f6f6f6; border-left: 1px solid rgba(255,255,255,0.375); border-right: 1px solid #ececec; border-right: 1px solid rgba(0,0,0,0.02); -webkit-background-origin: border !important; -moz-background-origin: border !important; background-origin: border !important; } table.slate tr:nth-child(odd) > td { text-shadow: 0px 1px 0px #ecf2fc; background: #dde8fa; background: -webkit-gradient(linear, left top, left bottom, from(#eaf1fb), to(#d1e0f9)); background: -moz-linear-gradient(top, #eaf1fb, #d1e0f9); text-shadow: 0px 1px 0px rgba(255,255,255,0.5);} table.slate tr:first-child > * { border-top: 1px solid #d0d0d0 !important; } table.slate tr > *:first-child { border-left: 1px solid #d0d0d0 !important; border-left: 1px solid rgba(0,0,0,0.1) !important; } table.slate tr > *:last-child { border-right: 1px solid #d0d0d0 !important; border-right: 1px solid rgba(0,0,0,0.1) !important; } table.slate tr:last-child > * { border-bottom: 1px solid #d0d0d0 !important; border-bottom: 1px solid rgba(0,0,0,0.2) !important; } table.slate, table.slate tbody, div#shadow, div#clip { -moz-border-radius-topleft: 0.625ex; -webkit-border-top-left-radius: 0.625ex; border-top-left-radius: 0.625ex; -moz-border-radius-topright: 0.625ex; -webkit-border-top-right-radius: 0.625ex; border-top-right-radius: 0.625ex; -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } table.slate tr:first-child { -moz-border-radius-topleft: 0.625ex; -webkit-border-top-left-radius: 0.625ex; border-top-left-radius: 0.625ex; -moz-border-radius-topright: 0.625ex; -webkit-border-top-right-radius: 0.625ex; border-top-right-radius: 0.625ex; } table.slate tr:last-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex;} table.slate tr:first-child > *:first-child { -moz-border-radius-topleft: 0.625ex; -webkit-border-top-left-radius: 0.75ex; border-top-left-radius: 0.75ex; } table.slate tr:first-child > *:last-child { -moz-border-radius-topright: 0.625ex; -webkit-border-top-right-radius: 0.75ex; border-top-right-radius: 0.75ex; } table.slate tr:last-child > *:first-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; } table.slate tr:last-child > *:last-child { -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } table.slate.clipboardExamples td .regex { -webkit-transition: opacity 0.33s cubic-bezier(0.2, 0.0, 0.5, 1.0); opacity: 1; } table.slate.clipboardExamples.inactive td .regex { -webkit-transition: opacity 0.33s cubic-bezier(0.5, 0.0, 0.75, 0.9); opacity: 0 !important; } table.slate.clipboardExamples { z-index: 10; position: relative; } table.slate.clipboardExamples.active { z-index: 99 !important; } table.slate.clipboardExamples#cbe_bg { z-index: 1; } table.slate.clipboardExamples.active td .regex { -moz-user-select: text; -webkit-user-select: text; cursor: auto; } table.slate.clipboardExamples#cbe_bg td > * { visibility: hidden; } table.slate.clipboardExamples#cbe_a th, table.slate.clipboardExamples#cbe_b th { visibility: hidden; } table.slate.clipboardExamples td .regex > del { display: none; } table.slate.clipboardExamples td .regex > ins { -webkit-transition: color 1s cubic-bezier(0.43, 0, 1.0, 0.75), text-shadow 0.65s cubic-bezier(0.43, 0, 1.0, 0.75); color: #202020; text-decoration: none; } table.slate.clipboardExamples.inactive td > .regex > ins { color: #f00; text-shadow: 1px 1px 3px rgba(255,0,0,0.66); } table.slate.clipboardExamples.transparentBackground, table.slate.clipboardExamples.transparentBackground * { border-color: transparent !important; background: transparent !important; } table.regexList .regexMatch { padding-right: 0.75ex; padding-left: 0.75ex; } /* even = light, odd = dark */ table.regexList tr:nth-child(odd) .regexMatch { border-right: 1px solid rgba(0,0,0,0.05); border-left: 1px solid rgba(255,255,255,0.5); } table.regexList tr:nth-child(even) .regexMatch { border-right: 1px solid rgba(0,0,0,0.04); border-left: 1px solid rgba(255,255,255,0.85); } table.regexList .regexMatch:first-child { padding-left: 0px; border-left: 0px solid transparent !important; } table.regexList .regexMatch:last-child { padding-right: 0px; border-right: 0px solid transparent !important; } table.slate.clipboardExamples { font-size: 12px; } table.slate > tbody > tr > td.code { font-size: 0.8334em; color: #202020; text-shadow: 0px 1px 0px rgba(255,255,255,0.75); } .tunableBreak { display: none; } .tbrOn { display: none; } .tbrOff { display: inline; } } /* This causes the ICU regex syntax tables to double up, side-by-side when the view port size > 1200. Otherwise, one follows the other for readability on small screens. */ @media screen and (max-width: 1100px) { div.table.regexSyntax, div.table.regexSyntax > .row, div.table.regexSyntax > .row > .cell { display: block; } div.table.regexSyntax > .row > .cell { width: 100%; } .metacharacters + .operators { margin-top: 1em; } .tunableBreak { display: inline; } .tbrOn { display: inline; } .tbrOff { display: none; } } @media screen and (max-width: 900px) { table.regexList .regex { white-space: pre-wrap; } .softNobr { white-space: pre-wrap; } } @media print { h2 { border-bottom: 1px solid #000; color: #000; } table.regexList .regex { white-space: pre-wrap; } table.standard th, table.regexList th { color: #000; border-bottom: 1px solid #9BB3CD; border-right: 1px solid #9BB3CD; border-bottom: 1px solid #919699; border-right: 1px solid #919699; background: #E2E2E2; } table.standard, table.regexSyntax { border-top: 1px solid #919699; border-left: 1px solid #919699; } .softNobr { white-space: pre-wrap; } .tbrOn { display: inline; } .tbrOff { display: none; } table.slate { border-spacing: 0px; border-top: 1px solid #919699; border-left: 1px solid #919699; } table.slate caption { margin-bottom: 0.5em; text-align: left; } table.slate caption > .identifier { font-weight: bold; margin-right: 1.5ex; } table.slate tr { -webkit-background-origin: border; -moz-background-origin: border; } table.slate th { padding: 0.3334em 1ex; border-bottom: 1px solid #919699; border-right: 1px solid #919699; background: #E2E2E2; -webkit-background-origin: border; -moz-background-origin: border; } table.slate td { padding-left: 0.75ex; padding-right: 0.75ex; padding-top: 0.1875em; padding-bottom: 0.1875em; border-bottom: 1px solid #919699; border-right: 1px solid #919699; -webkit-background-origin: border; -moz-background-origin: border; } table.regexList { width: 100%; } table.regexList .regexMatch { padding-right: 0.75ex; padding-left: 0.75ex; } table.regexList .regexMatch:first-child { padding-left: 0px; border-left: 0px solid transparent } table.regexList .regexMatch:last-child { padding-right: 0px; border-right: 0px solid transparent } table.slate { -moz-border-radius: 0.5ex; -webkit-border-radius: 0.5ex; border-radius: 0.5ex; } table.slate tr:first-child > *:first-child { -moz-border-radius-topleft: 0.5ex; -webkit-border-top-left-radius: 0.5ex; border-top-left-radius: 0.5ex; } table.slate tr:first-child > *:last-child { -moz-border-radius-topright: 0.5ex; -webkit-border-top-right-radius: 0.5ex; border-top-right-radius: 0.5ex; } table.slate tr:last-child > *:first-child { -moz-border-radius-bottomleft: 0.5ex; -webkit-border-bottom-left-radius: 0.5ex; border-bottom-left-radius: 0.5ex; } table.slate tr:last-child > *:last-child { -moz-border-radius-bottomright: 0.5ex; -webkit-border-bottom-right-radius: 0.5ex; border-bottom-right-radius: 0.5ex; } .screenOnly { display: none; } body { font: 10pt "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", helvetica, arial, sans-serif; margin: 0px; margin-left: 1.15in; /*width:100%;*/ /* margin-right: -0.4in;*/ /*margin-right: -1in;*/ /*width: 100%;*/ } h1 { padding-bottom: 0px; padding-top: 0.5em; margin-top: 2in; margin-bottom: 0.5em; border-top: 1px solid black; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; font-size: 27pt; } h2 { page-break-after: avoid; padding-bottom: 3.5em; padding-left: 0.6in; padding-top: 1em; margin-bottom: 2.5em; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; font-size: 24pt; } h3, .tasks .header, .guide .seealso > .header { padding-bottom: 0.25em; border-bottom: 1px solid black; page-break-after: avoid; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; font-size: 18pt; } h4 { padding-bottom: 0.25em; border-bottom: 1px solid black; page-break-after: avoid; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; } h5 { border-bottom: 1px solid black; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; } .titlePage h1 { font-size: 27pt; } .security { padding-left: 0.6in; } .security > .inner { margin-left: 0.5ex; } h1, h2, h3, .security { margin-left: -0.6in; } h1.reference { font-size: 24pt; margin-top: 2.5em; padding-bottom: 4em; padding-left: 0.6in; padding-top: 0px; margin-bottom: 0.5em; border-top: 0px; border-bottom: 1px solid black; } .reference h2 { page-break-before: avoid; page-break-after: avoid; border-bottom: 1px solid black; margin-top: 2.0em; margin-bottom: 0.5em; margin-right: 0px; margin-left: -0.6in; padding: 0px 0px 0.25em 0px; font-size: 18pt; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; } A:link, A:link:hover, A:active, A:active:hover, A:visited, A:visited:hover{ text-decoration: none; color: #000; } a.printURL:after { content: " (" attr(href) ")"; font-size: 85%; font-style: italic; } a.NBSP_printURL:after { content: "\00A0(" attr(href) ")"; font-size: 85%; font-style: italic; } a.printURL_small:after { content: " (" attr(href) ")"; font-size: 66%; font-style: italic; } a.NBSP_printURL_small:after { content: "\00A0(" attr(href) ")"; font-size: 66%; font-style: italic; } a.printURL_verySmall:after { content: " (" attr(href) ")"; font-size: 50%; font-style: italic; overflow: hidden; text-overflow: ellipsis; } a.NBSP_printURL_verySmall:after { content: "\00A0(" attr(href) ")"; font-size: 50%; font-style: italic; overflow: hidden; text-overflow: ellipsis; } .overview > .masthead { page-break-after: avoid; padding-bottom: 2.5em; margin-top: 0px; margin-bottom: 1.0em; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; } .printPageBreakBefore { page-break-before: always; } .printPageBreakAfter { page-break-after: always; } .titlePage .frameworkabstract { margin-left: -0.6in; font-size: 11pt; } .titlePage .dateAndRevision { font: bold 10pt Helvetica; margin-top: 5.25in; } table.standard { -moz-box-shadow: 2px 2px 1px #777; -webkit-box-shadow: 2px 2px 1px #777; } table.regexSyntax { -moz-box-shadow: 2px 2px 1px #777; -webkit-box-shadow: 2px 2px 1px #777; } table.slate { -moz-box-shadow: 2px 2px 1px #777; -webkit-box-shadow: 2px 2px 1px #777; } table.regexList { -moz-box-shadow: 2px 2px 1px #777; -webkit-box-shadow: 2px 2px 1px #777; } table.standard caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; } table.regexSyntax caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; } table.slate caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; } table.regexList caption { -moz-box-shadow: 0px 0px 0px #000; -webkit-box-shadow: 0px 0px 0px #000; } .table.standard { background-color: white; } .box .metainfo { font: 6.5pt "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; border-color: #999; background-color: white; } .box .metainfo.printShadow { -moz-box-shadow: 1px 1px 2px #bbb; -webkit-box-shadow: 1px 1px 2px #bbb; } .box .highlight { padding-top: 1pt; padding-bottom: 1pt; } .code, .regex, .regex-textual, .regex-def, .header_file, .file, .build-phase, .xcode-group, .xcode-target, .window-name, .box.sourcecode, .box.shell, .shellFont, .guide .sourceLicense pre, .signature, .block > .section.constants > .constant > .identifier, .dialog-option, .context-menu, .block.typedef > .section.code, .block.typedef > .section.type, .quotedText, .unicodeCharName, .block > .section.declaration, .regexMatch, .unicodeProperty, .consoleText, .section.parameters li > .name { font-size: 0.8334em !important; font-family: "Letter Gothic Std", "Letter Gothic", "LetterGothic", "Courier New", monaco, courier, monospace; } .regex-def, .cppTunables .cpp_flag, .cppTunables .code { font-size: 8pt !important; } table.regexSyntax.unicodeProperties .consoleText { font-size: 8pt !important; } .box .metainfo.noPrintBorder { margin-right: 0px; padding: 0px; border: 0px none transparent; background-color: white; -webkit-border-radius: 0px; -moz-border-radius: 0px; } .box .metainfo > .continues.above > .info { font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif !important; } .regex b { font: bold 1.1000em "Letter Gothic Std", "Letter Gothic", "LetterGothic", "Courier New", monaco, courier, monospace; } .syntax > .specification { font-family: "Letter Gothic Std", "Letter Gothic", "LetterGothic", "Courier New", monaco, courier, monospace; } .section.parameters ul { margin: 0px 0px 0px 0px; } .argument { font-family: "Letter Gothic Std", "Letter Gothic", "LetterGothic", "Courier New", monaco, courier, monospace; font-style: italic; font-size:0.85em; } .signature .argument { font-size: 1.02em; } /*.signature .argument { font-size: 8pt; }*/ .signature .selector, .signature .function { font-weight: bold; } .code .cpp_flag { font-weight: bold; font-size: 95%; } div.table.regexSyntax, div.table.regexSyntax > .row, div.table.regexSyntax > .row > .cell { display: block; } div.table.regexSyntax > .row > .cell { width: 100%; } .metacharacters + .operators { margin-top: 1em; } .syntax > .specification .parameter, .tasks .header .code, .method .name, .typedef .name { font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: normal; } .constants > .constant > .identifier, .code, .header_file, .file, .unicodeCharName { color: #000; } .box.tip { -webkit-border-radius: 0.85em; -moz-border-radius: 0.85em; } .box.sourcecode, .box.shell { margin-left: 0px; margin-right: 0px; padding: 0px; border: 1px solid white; background-color: white; -webkit-border-radius: 0px; } .box.sourcecode .comment { font-family: 'Lucida Sans Typewriter Std'; font-size: 8pt !important; } table, .box, .figure, .seealso, li, p, div.box.sourcecode { page-break-inside: avoid; } .regexSyntax .metacharacters table { page-break-before: avoid !important; page-break-inside: avoid !important; } .tasks > .header { font-size: 1.2500em; } .method > .name, .function > .name, .macro > .name, .typedef > .name { font-size: 1.2em; font-family: "Palatino LT Std", palatino, "Palatino Linotype", "URW Palladio L", "URWPalladioL", "Minion", "Minion Pro", georgia, times, "lucida grande", geneva, helvetica, arial, sans-serif; font-weight: bold; } .method, .function, .macro, .block.typedef { margin: 1.5em 0px 0px 0px; padding: 1.5em 0px 0px 0px; } .box.classSpecs { margin-left: 0px; font-size: 1.1em; } .box.hasRows { border: 0px none transparent; } .box.hasRows > .row > .cell { display: table-cell; padding: 1ex; border: 0px none transparent; } .box.hasRows > .row.lastRow > .cell { border: 0px none transparent !important; } .box.hasRows.zebraRows > .row.odd { background-color: white; } .box.hasRows > .row.headerRow { background-color: white; } .box.hasRows > .row.headerRow .cell { padding-top: 0.3334em; padding-bottom: 0.3334em; } .syntax > .specification .optional { -moz-box-shadow: 2px 3px 5px #888; -webkit-box-shadow: 2px 3px 5px #888; } .box.important, .box.note, .box.warning, .box.tip, .box.small, .box.quote { -moz-box-shadow: 2px 2px 1px #777; -webkit-box-shadow: 2px 2px 1px #777; } .box.caution { -moz-box-shadow: 0px 0px 5px #000; -webkit-box-shadow: 0px 0px 5px #000; } ul.overview { margin-left: 4.0ex; } .printNegLeft { font-size: 0.5em; } .constants > .constant > .text { margin-left: 0.4in; } .sourceLicense { page-break-inside: avoid; } .printImg { width: 100%; } .guide .seealso > .header { margin-top: 2.0em; margin-bottom: 0.5em; font-size: 1.5834em; } } </style> <script type="text/javascript"> var prefs = { current: { asNSString: true, escapeCopiedRegexes: true, escapeUnicodeCharacters: true, smartEscape: true, turnIntoString: true, unicodeInNSStrings: false, useC99: false }, defaults: { asNSString: true, escapeCopiedRegexes: true, escapeUnicodeCharacters: true, smartEscape: true, turnIntoString: true } }; var ui = { e: { cbe: { } }, pref: { map: {}, rows: [], controls: [], warnings: [] }, state: { interactiveInput: { updatePending: false }, copyToClipboardHUD: { ending: false, displayed: false, timeout: null }, regexTable: { readyForTransitions: false, timeout: null, last: "-", lastOptions: prefs } } }; var cache = { firstByteMark: [0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC], calculateStringDiff: { }, currentPrefs: ui.state.regexTable.lastOptions, diffString: { }, escapedString: { }, escapeCharacterEntities: { }, ui: { prefs: { prefWarningsHeight: 0 } } }; var utils = { browserInfo: { matches: { webKit: navigator.userAgent.match(/AppleWebKit\/(\d+(?:\.\d+)?)\b/), safari: navigator.userAgent.match(/AppleWebKit\/(\d+(?:\.\d+)?)\b.*?\sVersion\/((\d+(?:\.\d+)?)\b([^ ]*))\s.*?\bSafari\/([\d\.]+)\b/), xcode: navigator.userAgent.match(/AppleWebKit\/(\d+(?:\.\d+)?)\b.*?\bXcode\/([\d\.]+)\b/), opera: navigator.userAgent.match(/^Opera\/(\d+(?:\.\d+)?)/), mozilla: navigator.userAgent.match(/^Mozilla\/(\d+(?:\.\d+)?)\b.*\srv:(\d+(?:\.\d+)?)/), firefox: navigator.userAgent.match(/^Mozilla.*\s\w+\/(\d+)(?:\.(.*))?$/) } }, regex: { lt: /\u003c/g, gt: /\003e/g, amp: /\0026/g, newline: /\n/g, quote: /\"/g, specialChar: /(\\{1,1}?)([^\"\\])/g, specialCharPlusNewlines: /(?!\\\\[un])([^\\]\\(?=[\"n]))([^\"n])/g, escapedChar: /\\(?![0-7]{3}|[xX][a-fA-F0-9]+|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})/g, escapedCharPlusNewline: /\\(?![nvfr]|[0-7]{3}|[xX][a-fA-F0-9]+|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})/g, escapedHex: /\\?\\(?:[xX][a-fA-F0-9]+|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})/g, escapedOctal: /\\[0-7]{3}/g, px: /(.*)px$/, hidden: /\bhidden\b/, doNotEscape: /\bdoNotEscape\b/, marginAndOpacityTransition: /\bmarginAndOpacityTransition\b/ } }; if((utils.browserInfo.webKit = (utils.browserInfo.matches.webKit !== null) ? true : false) === true) { utils.browserInfo.webKitVersion = utils.browserInfo.matches.webKit[1]; } if((utils.browserInfo.safari = (utils.browserInfo.matches.safari !== null) ? true : false) === true) { utils.browserInfo.safariVersion = utils.browserInfo.matches.safari[3]; } if((utils.browserInfo.opera = (utils.browserInfo.matches.opera !== null) ? true : false) === true) { utils.browserInfo.operaVersion = utils.browserInfo.matches.opera[1]; } if((utils.browserInfo.mozilla = (utils.browserInfo.matches.mozilla !== null) ? true : false) === true) { utils.browserInfo.mozillaVersion = utils.browserInfo.matches.mozilla[1]; utils.browserInfo.geckoVersion = utils.browserInfo.matches.mozilla[2]; utils.browserInfo.firefoxVersion = utils.browserInfo.matches.firefox[1]; } if((utils.browserInfo.xcode = (utils.browserInfo.matches.xcode !== null) ? true : false) === true) { utils.browserInfo.xcodeVersion = utils.browserInfo.matches.xcode[2]; var wkver = utils.browserInfo.matches.xcode[1], safver = 1; utils.browserInfo.safari = true; if(wkver >= 419 && wkver < 525) { safver = 2; } else if(wkver >= 525 && wkver < 528) { safver = 3; } else if(wkver >= 528) { safver = 4; } utils.browserInfo.safariVersion = safver; } function getWidthInfo(element) { var style = document.defaultView.getComputedStyle(element, null); var info = { paddingLeft: style.paddingLeft, paddingRight: style.paddingRight, width: style.width, borderLeftWidth: style.borderLeftWidth, borderRightWidth: style.borderRightWidth }; for(var prop in info) { if(info[prop] !== undefined) { if(info[prop] === "auto") { info[prop] = 0; } else { var pxMatch = info[prop].match(utils.regex.px); if(pxMatch !== null) { info[prop] = Number(pxMatch[1]); } } } } info.elementOuterWidth = (info.borderLeftWidth + info.borderRightWidth + info.paddingLeft + info.paddingRight); info.elementFullWidth = (info.elementOuterWidth + info.width); return(info); } function escapeToCharacterEntities(string) { if(cache.escapeCharacterEntities[string] === undefined) { cache.escapeCharacterEntities[string] = string.replace(utils.regex.amp, "&amp;").replace(utils.regex.lt, "&lt;").replace(utils.regex.gt, "&gt;"); } return(cache.escapeCharacterEntities[string]); } function calculateStringDiff(A, B) { if((cache.calculateStringDiff[A] !== undefined) && (cache.calculateStringDiff[A][B] !== undefined)) { return(cache.calculateStringDiff[A][B]); } var i = 0, j = 0, L = [], D = {A: A, B: B, length: 0, same: [], del: [], ins: []}; for(var x = -1; x < A.length + 3; x++) { L[x] = []; for (var y = -1; y < B.length + 3; y++) { L[x][y] = 0; } } for (i = A.length; i >= 0; i--) { for (j = B.length; j >= 0; j--) { if(A[i] === B[j]) { L[i][j] = 1 + L[i+1][j+1]; } else { L[i][j] = ((L[i+1][j] > L[i][j+1]) ? L[i+1][j] : L[i][j+1]); } } } i = j = 0; while((i <= A.length) && (j <= B.length)) { if((i === A.length) && (j === B.length)) { break; } if(A[i] === B[j]) { D.same[D.length] = A[i]; D.length++; i++; j++; } else if(L[i+1][j] >= L[i][j+1]) { D.del[D.length] = A[i]; D.length++; i++; } else { D.ins[D.length] = B[j]; D.length++; j++; } } if(cache.calculateStringDiff[A] === undefined) { cache.calculateStringDiff[A] = {}; } if(cache.calculateStringDiff[A][B] === undefined) { cache.calculateStringDiff[A][B] = D; } return(D); } function diffString(A, B) { if((cache.diffString[A] !== undefined) && (cache.diffString[A][B] !== undefined)) { return(cache.diffString[A][B]); } var D = calculateStringDiff(A, B), DS = "", lastFrom = 0; for(var x = 0; x < D.length; x++) { if(D.same[x] !== undefined) { DS += ((lastFrom === 0) ? "" : (lastFrom === 1) ? "\u003c/ins\u003e" : "\u003c/del\u003e") + escapeToCharacterEntities(D.same[x]); lastFrom = 0; } else if(D.ins[x] !== undefined) { DS += ((lastFrom === 0) ? "\u003cins\u003e" : (lastFrom === 1) ? "" : "\u003c/del\u003e\u003cins\u003e") + escapeToCharacterEntities(D.ins[x]); lastFrom = 1; } else if(D.del[x] !== undefined) { DS += ((lastFrom === 0) ? "\u003cdel\u003e" : (lastFrom === 1) ? "\u003c/ins\u003e\u003cdel\u003e" : "") + escapeToCharacterEntities(D.del[x]); lastFrom = 2; } } DS += ((lastFrom === 0) ? "" : (lastFrom === 1) ? "\u003c/ins\u003e" : "\u003c/del\u003e"); if(cache.diffString[A] === undefined) { cache.diffString[A] = {}; } if(cache.diffString[A][B] === undefined) { cache.diffString[A][B] = DS; } return(DS); } function isSimpleCString(cstr) { var escapedArray, i; for(i = 0; i < cstr.length; i++) { if(cstr.charCodeAt(i) > 127) { return(false); } } if((escapedArray = cstr.match(utils.regex.escapedOctal)) !== null) { for(i = 0; i < escapedArray.length; i++) { if(parseInt(escapedArray[i].substr(1), 8) >= 0x80) { return(false); } } } if((escapedArray = cstr.match(utils.regex.escapedHex)) !== null) { for(i = 0; i < escapedArray.length; i++) { if(escapedArray[i].search(/\\\\/) !== -1) { continue; } if(parseInt(escapedArray[i].substr(2), 16) >= 0x80) { return(false); } } } return(true); } function stringToEscapedString(string, options) { if(options.escapeCopiedRegexes !== true) { return(string); } if((cache.escapedString[string] !== undefined) && (cache.escapedString[string][options.key] !== undefined)) { return(cache.escapedString[string][options.key]); } var es = "", s = string; if(options.smartEscape === false) { s = s.replace(/\\/g, "\\\\"); } else { s = s.replace(/(\\?)(\\(?:x[a-fA-F0-9]{2}|u([a-fA-F0-9]{4})))/g, function(m0, m1, m2, m3) { return(((m1 === "\\") ? m0 : eval("\"" + m2 + "\""))); }); s = s.replace(/(\\?)(\\(?:U([a-fA-F0-9]{8})))/g, function(m0, m1, m2, m3) { if(m1 === "\\") { return(m0); } var u32 = parseInt(m3, 16); if(u32 > 0xffff) { var ul = "\\u" + ("0000" + (0xd7c0 + (u32 >> 10)).toString(16)).substr(-4,4); var uh = "\\u" + ("0000" + (0xdc00 + (u32 & 0x3ff)).toString(16)).substr(-4,4); return(eval("\"" + ul + uh + "\"")); } else { return(eval("\"\\u" + (("0000" + u32.toString(16)).substr(-4,4)) + "\"")); } }); s = s.replace(/(.?)(\\)(?!\\)(u[0-9a-fA-F]{4}|.?)/g, function(m0, m1, m2, m3) { return(((m3.search(/n|u[0-9a-fA-F]{4}/) !== -1) ? m0 : ((((m1 === "\\")) ? "\\\\" : m1) + "\\\\" + m3))) }); } s = s.replace(utils.regex.quote, "\\\""); // " for(var i = 0; i < s.length; i++) { var u32 = s.charCodeAt(i), u16h = 0, u16l = 0; // If u32 is the start of a UTF16 surrogate pair, get the high surrogate and convert to a UTF32 codepoint. if(((u16h = u32) >= 0xd800) && (u16h <= 0xdbff)) { u32 = ((u16h - 0xd7c0) << 10) | ((u16l = s.charCodeAt(++i)) - 0xdc00); } if((u32 >= 0x20) && (u32 < 0x7f)) { es += String.fromCharCode(u32); } // Use printable 7 bit ascii directly. else { switch(u32) { // Pretty escape some characters. case 10: es += (options.smartEscape ? "\\n" : "\\\\n"); break; //case 11: es += (options.smartEscape ? "\\v" : "\\\\v"); break; //case 12: es += (options.smartEscape ? "\\f" : "\\\\f"); break; //case 13: es += (options.smartEscape ? "\\r" : "\\\\r"); break; default: if(options.escapeUnicodeCharacters === false) { es += String.fromCharCode(u16h); if(u16l !== 0) { es += String.fromCharCode(u16l); } } else { if(options.smartEscape === false) { if(u32 < 0x10000) { es += "\\\\u" + ("0000" + u32.toString(16)).substr(-4,4); } else { es += "\\\\U" + ("00000000" + u32.toString(16)).substr(-8,8); } } else { // C99 6.4.3.2, only 0024 '$', 0040 '@', or 0060 '`' can be specified via \u when < \u00a0. if((options.useC99 === true) && (u32 >= 0xa0)) { if(u32 < 0x10000) { es += "\\u" + ("0000" + u32.toString(16)).substr(-4,4); } else { es += "\\U" + ("00000000" + u32.toString(16)).substr(-8,8); } } else { var x, ch = u32, utf8 = [], bytes = (ch < 0x80) ? 1 : (ch < 0x800) ? 2 : (ch < 0x10000) ? 3 : 4; for(x = bytes; x > 0; x--) { utf8.unshift((ch | ((x > 1) ? 0x80 : cache.firstByteMark[bytes])) & ((x > 1) ? 0xBF : 0xFF)); ch >>= 6; } for(x = 0; x < utf8.length; x++) { es += "\\"+("000" + utf8[x].toString(8)).substr(-3,3); } } } } } } } if(options.turnIntoString === true) { es = '"' + es + '"'; if(options.asNSString) { es = ((isSimpleCString(es) || options.unicodeInNSStrings || !options.smartEscape) ? "@" + es : '[NSString stringWithUTF8String:' + es + ']'); } } if(options.cache === true) { if(cache.escapedString[string] === undefined) { cache.escapedString[string] = {}; } if(cache.escapedString[string][options.key] === undefined) { cache.escapedString[string][options.key] = es; } } return(es); } function updateRegexEscapedExampleTable(uiForCBE) { for(var x = 0; x < exampleRegexArray.length; x++) { smartElementUpdate(uiForCBE.row[x].regex, "innerHTML", escapeToCharacterEntities(exampleRegexArray[x])); smartElementUpdate(uiForCBE.row[x].escape, "innerHTML", escapeToCharacterEntities(exampleRegexArray[x].toPrefsEscapedString())); } } function updateRegexEscapedExampleTableNew(uiForCBE_a, uiForCBE_b) { for(var x = 0; x < exampleRegexArray.length; x++) { smartElementUpdate(uiForCBE_b.row[x].escape, "innerHTML", diffString(stringToEscapedString(exampleRegexArray[x], ui.state.regexTable.lastOptions), exampleRegexArray[x].toPrefsEscapedString())); } uiForCBE_a.table.className = uiForCBE_a.table.className.replace(/\bactive\b/, "inactive"); uiForCBE_b.table.className = uiForCBE_b.table.className.replace(/\binactive\b/, "active"); } function updateRegexEscapedExamples() { var cbe_a = ui.e.cbe.a, cbe_b = ui.e.cbe.b; if(ui.state.regexTable.last === "a") { updateRegexEscapedExampleTableNew(cbe_a, cbe_b); ui.state.regexTable.last = "b"; } else { updateRegexEscapedExampleTableNew(cbe_b, cbe_a); ui.state.regexTable.last = "a"; } ui.state.regexTable.lastOptions = cache.currentPrefs; } function removeClassFromElement(classToRemove, element) { var classMatch, left = new RegExp("\\s?\\b" + classToRemove + "\\b"), right = new RegExp("\\b" + classToRemove + "\\b\\s?"); if((classMatch = element.className.match(new RegExp("(\\s?)\\b" + classToRemove + "\\b(\\s?)"))) !== null) { element.className = element.className.replace((((classMatch[1] !== undefined) && (classMatch[1].length > 0)) ? left : right), ""); } } function setTransitionElement(element, visible, height) { if(visible === true) { if(element.className.search(utils.regex.hidden) !== -1) { removeClassFromElement("hidden", element); } smartElementUpdate(element.style, "marginBottom", "0px"); } else { if(element.className.search(utils.regex.hidden) === -1) { element.className += " hidden"; } smartElementUpdate(element.style, "marginBottom", "-" + height + "px"); } } function smartElementUpdate(e, i, val) { if(e[i] !== val) { e[i] = val; } } function updatePrefsUI() { var e, x; for(x = 0; x < ui.pref.controls.length; x++) { if((e = ui.pref.controls[x]).nodeName === "SELECT") { continue; } smartElementUpdate(e, "checked", prefs.current[ui.pref.map[e.id]]); } if(prefs.current.escapeCopiedRegexes === false) { smartElementUpdate(ui.e.copyRegexPrefsStyle[0], "selected", true); smartElementUpdate(ui.e.copyRegexPrefsStyle[1], "selected", false); smartElementUpdate(ui.e.copyRegexPrefsStyle[2], "selected", false); smartElementUpdate(ui.e.copyRegexPrefsStyle[3], "selected", false); for(x = 0; x < ui.pref.controls.length; x++) { if((e = ui.pref.controls[x]).nodeName === "SELECT") { continue; } smartElementUpdate(e, "disabled", true); } for(x = 0; x < ui.pref.rows.length; x++) { smartElementUpdate(ui.pref.rows[x], "className", "copyRegexPrefsRow disabledPref"); } } else { var turnIntoNSString = (prefs.current.turnIntoString && prefs.current.asNSString); smartElementUpdate(ui.e.copyRegexPrefsStyleRow, "className", "copyRegexPrefsRow enabledPref"); smartElementUpdate(ui.e.copyRegexPrefsStyle[0], "selected", false); smartElementUpdate(ui.e.copyRegexPrefsStyle[1], "selected", !prefs.current.turnIntoString); smartElementUpdate(ui.e.copyRegexPrefsStyle[2], "selected", prefs.current.turnIntoString && !prefs.current.asNSString); smartElementUpdate(ui.e.copyRegexPrefsStyle[3], "selected", turnIntoNSString); smartElementUpdate(ui.e.copyRegexPrefsSmartEscape, "disabled", false); smartElementUpdate(ui.e.copyRegexPrefsSmartEscapeRow, "className", "copyRegexPrefsRow enabledPref"); //smartElementUpdate(ui.e.copyRegexPrefsEscapeUnicodeCharacters, "disabled", false); //smartElementUpdate(ui.e.copyRegexPrefsEscapeUnicodeCharactersRow, "className", "copyRegexPrefsRow enabledPref"); smartElementUpdate(ui.e.copyRegexPrefsUseC99, "disabled", !prefs.current.smartEscape || !prefs.current.escapeUnicodeCharacters); smartElementUpdate(ui.e.copyRegexPrefsUseC99Row, "className", ((prefs.current.smartEscape && prefs.current.escapeUnicodeCharacters) ? "copyRegexPrefsRow enabledPref" : "copyRegexPrefsRow disabledPref")); smartElementUpdate(ui.e.copyRegexPrefsUnicodeInNSStrings, "disabled", !turnIntoNSString || !prefs.current.smartEscape); smartElementUpdate(ui.e.copyRegexPrefsUnicodeInNSStringsRow, "className", ((turnIntoNSString && prefs.current.smartEscape) ? "copyRegexPrefsRow enabledPref" : "copyRegexPrefsRow disabledPref")); } if(ui.state.regexTable.readyForTransitions === true) { var showPrefWarnings = false, showSmartEscapeWarning = false, showNSStringUnicodeWarning = false, showC99Warning = false; if(prefs.current.escapeCopiedRegexes === true) { showSmartEscapeWarning = (!ui.e.copyRegexPrefsSmartEscape.disabled && prefs.current.smartEscape); showNSStringUnicodeWarning = (!ui.e.copyRegexPrefsUnicodeInNSStrings.disabled && prefs.current.unicodeInNSStrings); showC99Warning = (!ui.e.copyRegexPrefsUseC99.disabled && prefs.current.useC99); showPrefWarnings = (prefs.current.smartEscape || showNSStringUnicodeWarning || showC99Warning); } setTransitionElement(ui.e.smartEscapeWarning, showSmartEscapeWarning, cache.ui.prefs.smartEscapeWarning); setTransitionElement(ui.e.c99Warning, showC99Warning, cache.ui.prefs.c99Warning); setTransitionElement(ui.e.nsstringUnicodeWarning, showNSStringUnicodeWarning, cache.ui.prefs.nsstringUnicodeWarning); setTransitionElement(ui.e.prefWarnings, showPrefWarnings, cache.ui.prefs.prefWarningsHeight); } updateRegexEscapedExamples(); ui.e.interactiveEscapedOutput.innerHTML = escapeToCharacterEntities(ui.e.interactiveEscapedInput.value.toPrefsEscapedString()); } function prefsEscapedStringOptions() { var prop, options = {}, prefsArray = []; for(prop in prefs.current) { options[prop] = prefs.current[prop]; prefsArray.push(prefs.current[prop]); } options.key = prefsArray.join(""); return(options); } String.prototype.toPrefsEscapedString = function () { if(utils.browserInfo.opera === true) { cache.currentPrefs.cache = true; } else { if(String.prototype.toPrefsEscapedString.caller) { cache.currentPrefs.cache = (((String.prototype.toPrefsEscapedString.caller.caller)) ? true : false); } } return((prefs.current.escapeCopiedRegexes !== true) ? this : stringToEscapedString(this, cache.currentPrefs)); }; function setPrefsCookie() { var distantFuture = new Date(), prefsArray = [], prop; distantFuture.setFullYear(2038); for(prop in prefs.current) { prefsArray.push(prop + ": " + prefs.current[prop]); } document.cookie = 'prefs="' + escape(prefsArray.join(", ")) + '"; expires=' + distantFuture.toGMTString(); cache.currentPrefs = prefsEscapedStringOptions(); updatePrefsUI(); } function setPrefsFromCookie() { var prefsCookie = document.cookie.match(/prefs=\"(.*)\";?/); if(prefsCookie !== null) { var evalPrefs = "var prefsFromCookie = {" + unescape(prefsCookie[1]) + "};\n" + prefs.setFromCookie; try { eval(evalPrefs); } catch(e) { console.warn("Unable to set copy to clipboard preference from cookie. Resetting prefs cookie."); console.debug("eval '" + evalPrefs + "' = " + e); if(console.dir) { console.dir(e); } document.cookie = 'prefs="";'; } } for(var prop in prefs.defaults) { var cp = prefs.current[prop]; if((cp !== false) && (cp !== true)) { cp = prefs.defaults[prop]; } } cache.currentPrefs = prefsEscapedStringOptions(); setPrefsCookie(); } function timestampString() { var now = new Date(); return(now.getFullYear() + "-" + ("00" + now.getMonth()).substr(-2,2) + "-" + ("00" + now.getDay()).substr(-2,2) + " " + ("00" + now.getHours()).substr(-2,2) + ":" + ("00" + now.getMinutes()).substr(-2,2) + ":" + ("00" + now.getSeconds()).substr(-2,2) + "." + ("000" + now.getMilliseconds()).substr(-3,3) + " "); } function cleanupColorTransition(element) { var now = ["pulseOutline", "transitionColor"]; var delayed = ["transitionRed", "transitionGreen", "transitionBlue", "pulseOutlineRed"]; now.forEach(function(what) { removeClassFromElement(what, element); }); delayed.forEach(function(what) { window.setTimeout(function() { removeClassFromElement(what, element); }, 1); }); } function endTransitionColor(event) { cleanupColorTransition(event.target); } function setCopyToClipboardHUD(hudString) { if(ui.state.copyToClipboardHUD.displayed === true) { window.clearTimeout(ui.state.copyToClipboardHUD.timeout); ui.state.copyToClipboardHUD.timeout = null; ui.e.copyToClipboardHUD.style.top = window.pageYOffset + "px"; var originalWidth = ui.e.copyToClipboardHUD.style.width; removeClassFromElement("copyToClipboardHUDAnimate", ui.e.copyToClipboardHUD); window.setTimeout(function() { ui.e.copyToClipboardHUD.style.width = ""; ui.e.copyToClipboardHUDRegex.replaceChild(document.createTextNode(hudString), ui.e.copyToClipboardHUDRegex.childNodes[0]); var updateWidth = Math.min(Number(ui.e.copyToClipboardHUD.clientWidth), Math.floor(window.outerWidth * 0.9)); var updateLeft = ((Number(document.width) / 2) - (updateWidth / 2)); ui.e.copyToClipboardHUD.style.width = originalWidth; window.setTimeout(function () { ui.e.copyToClipboardHUD.className += " copyToClipboardHUDAnimate"; window.setTimeout(function () { ui.e.copyToClipboardHUD.style.left = updateLeft + "px"; ui.e.copyToClipboardHUD.style.width = updateWidth + "px"; }, 3); }, 5); }, 7); } else { ui.state.copyToClipboardHUD.displayed = true; ui.e.copyToClipboardHUDRegex.replaceChild(document.createTextNode(hudString), ui.e.copyToClipboardHUDRegex.childNodes[0]); smartElementUpdate(ui.e.copyToClipboardHUD.style, "display", "block"); smartElementUpdate(ui.e.copyToClipboardHUD.style, "position", "absolute"); ui.e.copyToClipboardHUD.style.top = (window.pageYOffset +1) + "px"; var updateWidth = Math.min(Number(ui.e.copyToClipboardHUD.clientWidth), Math.floor(window.outerWidth * 0.9)); var updateLeft = ((Number(document.width) / 2) - (updateWidth / 2)); ui.e.copyToClipboardHUD.style.left = updateLeft + "px"; ui.e.copyToClipboardHUD.style.width = updateWidth + "px"; window.setTimeout(function() { ui.e.copyToClipboardHUD.className += " copyToClipboardHUDAnimate"; }, 7); } ui.state.copyToClipboardHUD.timeout = window.setTimeout(function() { ui.e.copyToClipboardHUD.style.top = (window.pageYOffset - (ui.e.copyToClipboardHUD.clientHeight + 10)) + "px"; ui.state.copyToClipboardHUD.ending = true; ui.state.copyToClipboardHUD.timeout = window.setTimeout(function() { removeClassFromElement("copyToClipboardHUDAnimate", ui.e.copyToClipboardHUD); ui.e.copyToClipboardHUD.style.display = "none"; ui.state.copyToClipboardHUD.ending = false; ui.state.copyToClipboardHUD.displayed = false; ui.state.copyToClipboardHUD.timeout = null; ui.e.copyToClipboardHUD.style.top = ""; ui.e.copyToClipboardHUD.style.left = ""; ui.e.copyToClipboardHUD.style.width = ""; }, 251); }, 3001); } function flattenChildren(element) { var flatArray = [element]; for(var x = 0; x < element.children.length; x++) { var child = element.children[x]; if(child.children.length > 0) { flatArray = flatArray.concat(flattenChildren(child)); } else { flatArray.push(child); } } return(flatArray); } function copySelectionToClipboard(element, event) { var selection = window.getSelection(); var selectionRange = selection.getRangeAt(0); var selectionElement = selectionRange.commonAncestorContainer; var selectionParent = selectionElement.parentNode; var isTextArea = (element.isSameNode(ui.e.interactiveEscapedInput) ? true : false); if((prefs.current.escapeCopiedRegexes !== false) && ((window.getSelection().rangeCount === 1) || (isTextArea === true))) { if((selectionElement.childNodes.length !== 0) && (isTextArea !== true)) { // Check and see if we can narrow things down a bit. // For example, tripple clicking a regex in one of the cookbook tables selects the regex + a bit of the cell. // We can safely narrow things down to just the whole regex in that case. var regexArray = selectionElement.getElementsByClassName("regex"); if(regexArray.length !== 1) { var intersectionArray = []; intersectionArray = flattenChildren(selectionElement).filter(function(e,i,a) { return(selectionRange.intersectsNode(e) && (e.childNodes.length === 1) && (e.childNodes[0].nodeName === "#text") && (selectionRange.isPointInRange(e.childNodes[0], 0) || selectionRange.isPointInRange(e.childNodes[0], e.childNodes[0].length))); }); if(intersectionArray.length !== 1) { return; } regexArray = intersectionArray; selectionRange.selectNodeContents(regexArray[0]); selectionElement = regexArray[0].childNodes[0]; selectionParent = regexArray[0]; } if(selectionRange.toString() != regexArray[0].childNodes[0].textContent) { return; } selectionParent = regexArray[0]; selectionElement = selectionParent.childNodes[0]; if(selectionElement.childNodes.length !== 0) { return; } selectionRange.selectNodeContents(selectionElement); } var copyString = selectionRange.toString().toPrefsEscapedString(); event.clipboardData.setData("text/plain", copyString); event.preventDefault(); setCopyToClipboardHUD(copyString); if(isTextArea === true) { cleanupColorTransition(element); window.setTimeout(function() { element.className += " pulseOutlineRed"; window.setTimeout(function() { element.className += " pulseOutline"; window.setTimeout(function() { removeClassFromElement("pulseOutlineRed", element); }, 17); }, 13); }, 11); element.addEventListener('webkitTransitionEnd', endTransitionColor); window.setTimeout(function() { cleanupColorTransition(element); }, 613.0); } else { var clonedSelectionElement = selectionElement.cloneNode(); var text = selectionElement.textContent, start = selectionRange.startOffset, end = selectionRange.endOffset; var startNode = document.createTextNode(text.substring(0, start)); var midNode = document.createTextNode(text.substring(start, end)); var endNode = document.createTextNode(text.substring(end)); var spanNode = document.createElement("span"); spanNode.appendChild(midNode); while(selectionParent.childNodes.length > 0) { selectionParent.removeChild(selectionParent.childNodes[0]); } selectionParent.appendChild(startNode); selectionParent.appendChild(spanNode); selectionParent.appendChild(endNode); spanNode.style.WebkitBoxShadow = "0px 0px 12px rgba(255,0,0,1.0)"; spanNode.style.background = "highlight !important"; window.setTimeout(function() { spanNode.className = "pulseOutline"; window.setTimeout(function() { spanNode.style.WebkitBoxShadow = "0px 0px 12px rgba(255,0,0,0.0)"; }, 5.0); }, 3.0); window.setTimeout(function() { while(selectionParent.childNodes.length > 0) { selectionParent.removeChild(selectionParent.childNodes[0]); } selectionParent.appendChild(clonedSelectionElement); var origNode = selectionParent.childNodes[0], resetRange = document.createRange(); resetRange.setStart(origNode, start); resetRange.setEnd(origNode, end); selection.removeAllRanges(); selection.addRange(resetRange); }, 607); } } } function buildPreviewTables(tableID, tableAttributesString, regexArray) { var rowArray = [], maxLength = 0, x; for(x = 0; x < regexArray.length; x++) { var regexLength = stringToEscapedString(regexArray[x], { escapeRegex: true, useC99: false, asNSString: true, unicodeInNSStrings: false }).length; maxLength = (maxLength < regexLength) ? regexLength : maxLength; } maxLength -= 2; rowArray.push("\u003ctable class=\"slate clipboardExamples\" id=\"" + tableID + "\" " + tableAttributesString + "\u003e"); rowArray.push(" \u003ctr\u003e\u003cth id=\"" + tableID + "_th_0\"\u003eSelection\u003c/th\u003e\u003cth id=\"" + tableID + "_th_1\"\u003eCopied to clipboard as&hellip;\u003c/th\u003e\u003c/tr\u003e"); for(x = 0; x < regexArray.length; x++) { rowArray.push(" \u003ctr id=\"" + tableID + "_row_" + x + "\"\u003e\u003ctd id=\"" + tableID + "_td_0_" + x + "\" class='unescaped'\u003e\u003cspan class=\"regex\" id=\"" + tableID + "_regex_" + x + "\"\u003e&nbsp;\u003c/span\u003e\u003c/td\u003e\u003ctd id=\"" + tableID + "_td_1_" + x + "\" class='escaped'\u003e\u003cspan class=\"regex doNotEscape\" id=\"" + tableID + "_escape_" + x + "\"\u003e&nbsp;\u003c/span\u003e\u003c/td\u003e\u003c/tr\u003e"); } rowArray.push("\u003c/table\u003e"); return(rowArray.join("\n")); } function copyRegexPrefsStyleChanged() { switch(ui.e.copyRegexPrefsStyle.options.selectedIndex) { case 0: prefs.current.escapeCopiedRegexes = false; prefs.current.turnIntoString = false; prefs.current.asNSString = false; break; case 1: prefs.current.escapeCopiedRegexes = true; prefs.current.turnIntoString = false; prefs.current.asNSString = false; break; case 2: prefs.current.escapeCopiedRegexes = true; prefs.current.turnIntoString = true; prefs.current.asNSString = false; break; case 3: prefs.current.escapeCopiedRegexes = true; prefs.current.turnIntoString = true; prefs.current.asNSString = true; break; } setPrefsCookie(); } function interactiveEscapedInputChanged() { if(ui.state.interactiveInput.updatePending === false) { window.setTimeout(function() { ui.e.interactiveEscapedOutput.innerHTML = escapeToCharacterEntities(ui.e.interactiveEscapedInput.value.toPrefsEscapedString()); ui.state.interactiveInput.updatePending = false; }, 127.0); ui.state.interactiveInput.updatePending = true; } } function initUIForCBE(id) { ui.e.cbe[id] = {}; ui.e.cbe[id].table = document.getElementById("cbe_"+id);; ui.e.cbe[id].th = {}; ui.e.cbe[id].th[0] = document.getElementById("cbe_"+id+"_th_0"); ui.e.cbe[id].th[1] = document.getElementById("cbe_"+id+"_th_1"); ui.e.cbe[id].row = {}; for(var x = 0; x < exampleRegexArray.length; x++) { ui.e.cbe[id].row[x] = {}; ui.e.cbe[id].row[x].td = {}; ui.e.cbe[id].row[x].tr = document.getElementById("cbe_"+id+"_row_" + x); ui.e.cbe[id].row[x].td[0] = document.getElementById("cbe_"+id+"_td_0_" + x); ui.e.cbe[id].row[x].td[1] = document.getElementById("cbe_"+id+"_td_1_" + x); ui.e.cbe[id].row[x].regex = document.getElementById("cbe_"+id+"_regex_" + x); ui.e.cbe[id].row[x].escape = document.getElementById("cbe_"+id+"_escape_" + x); } } function sheetIndexAndRuleIndexOfCSSRule(name) { for(var x = 0; x < document.styleSheets.length; x++) { var sheet = document.styleSheets[x]; for(var i = 0; i < sheet.cssRules.length; i++) { if(sheet.cssRules[i].selectorText === name) { return({sheet: x, rule: i}); } } } return(null); } function deleteCSSRule(name) { var sheetAndRule; if((sheetAndRule = sheetIndexAndRuleIndexOfCSSRule(name)) !== null) { document.styleSheets[sheetAndRule.sheet].deleteRule(sheetAndRule.rule); } } function setExampleTablesWidth(width) { for(var x = 0; x < exampleRegexArray.length; x++) { ui.e.cbe.bg.row[x].td[1].style.width = width; ui.e.cbe.a.row[x].td[1].style.width = width; ui.e.cbe.b.row[x].td[1].style.width = width; ui.e.cbe.bg.row[x].td[1].style.maxWidth = width; ui.e.cbe.a.row[x].td[1].style.maxWidth = width; ui.e.cbe.b.row[x].td[1].style.maxWidth = width; } } function updateExamplesTable() { setExampleTablesWidth(""); setExampleTablesWidth((getWidthInfo(ui.e.topContainer).width - getWidthInfo(ui.e.cbe.bg.row[0].td[0]).elementFullWidth - getWidthInfo(ui.e.cbe.bg.row[0].td[1]).elementOuterWidth) + "px"); } function updatePrefWarningsMargins() { var x, e; removeClassFromElement("marginAndOpacityTransition", ui.e.prefWarnings); for(x = 0; x < ui.pref.warnings.length; x++) { removeClassFromElement("marginAndOpacityTransition", (e = ui.pref.warnings[x])); smartElementUpdate(e.style, "marginBottom", "0px"); } for(x = 0; x < ui.pref.warnings.length; x++) { e = ui.pref.warnings[x]; cache.ui.prefs[e.id] = parseInt(document.defaultView.getComputedStyle(e, null).marginTop, 10) + e.clientHeight; e.style.marginBottom = "-" + cache.ui.prefs[e.id] + "px"; } cache.ui.prefs.prefWarningsHeight = Number(ui.e.prefWarnings.clientHeight); updatePrefsUI(); if(ui.state.regexTable.timeout !== null) { window.clearTimeout(ui.state.regexTable.timeout); ui.state.regexTable.timeout = null; } ui.state.regexTable.timeout = window.setTimeout(function() { ui.state.regexTable.timeout = null; if(ui.e.prefWarnings.className.search(utils.regex.marginAndOpacityTransition) === -1) { ui.e.prefWarnings.className += " marginAndOpacityTransition"; } for(var x = 0; x < ui.pref.warnings.length; x++) { if(ui.pref.warnings[x].className.search(utils.regex.marginAndOpacityTransition) === -1) { ui.pref.warnings[x].className += " marginAndOpacityTransition"; } } }, 31); } function handleResize() { updateExamplesTable(); updatePrefWarningsMargins(); } function initEnhancedCopyToClipboard() { var x, e, eArray = ["prefWarnings", "interactiveEscapedInput", "interactiveEscapedOutput", "copyToClipboardHUD", "copyToClipboardHUDTop", "copyToClipboardHUDRegex", "topContainer"]; for(x = 0; x < eArray.length; x++) { e = eArray[x]; ui.e[e] = document.getElementById(e); } for(x = 0, eArray = document.getElementsByClassName("copyRegexPrefsRow"); x < eArray.length; x++) { e = eArray[x]; ui.e[e.id] = e; ui.pref.rows.push(e); } for(x = 0, eArray = document.getElementsByClassName("copyRegexPrefsControl"); x < eArray.length; x++) { e = eArray[x]; ui.e[e.id] = e; ui.pref.controls.push(e); } for(x = 0, eArray = document.getElementsByClassName("copyRegexPrefsWarning"); x < eArray.length; x++) { e = eArray[x]; ui.e[e.id] = e; ui.pref.warnings.push(e); } for(x = 0, eArray = ui.pref.controls; x < eArray.length; x++) { if((e = eArray[x]).nodeName === "SELECT") { continue; } var m = e.id.match(/copyRegexPrefs(.)(.*)/); var n = m[1].toLowerCase() + m[2]; ui.pref.map[e.id] = n; eval("top." + e.id + "Changed = function() { prefs.current." + n + " = ui.e." + e.id + ".checked; setPrefsCookie(); }; ui.e." + e.id + ".addEventListener('change', top." + e.id + "Changed, false); ui.e." + e.id + "Row.getElementsByClassName('UIcontrolLabel')[0].childNodes[0].addEventListener('click', function() { ui.e." + e.id + ".checked = !ui.e." + e.id + ".checked; top." + e.id + "Changed(); }, false);"); if(prefs.current[n] === undefined) { prefs.current[n] = false; } if(prefs.defaults[n] === undefined) { prefs.defaults[n] = false; } } ui.e.copyRegexPrefsStyle.addEventListener("change", copyRegexPrefsStyleChanged, false); ui.e.interactiveEscapedInput.addEventListener("keyup", interactiveEscapedInputChanged, false); var prop, prefsArray = []; for(prop in prefs.defaults) { prefsArray.push(prop + ": prefsFromCookie." + prop); } prefs.setFromCookie = "prefs.current = { " + prefsArray.join(", ") + "};"; ui.e.interactiveEscapedInput.addEventListener("input", interactiveEscapedInputChanged, false); initUIForCBE("bg"); initUIForCBE("a"); initUIForCBE("b"); var cbe_bg = ui.e.cbe.bg, cbe_a = ui.e.cbe.a, cbe_b = ui.e.cbe.b; setPrefsFromCookie(); for(x = 0; x < exampleRegexArray.length; x++) { cbe_bg.row[x].regex.innerHTML = escapeToCharacterEntities(exampleRegexArray[x]); cbe_bg.row[x].escape.innerHTML = escapeToCharacterEntities(exampleRegexArray[x].toPrefsEscapedString()); } deleteCSSRule(".safariOnly"); deleteCSSRule(".enhancedCopyOnly"); updateRegexEscapedExampleTable(cbe_bg); updateRegexEscapedExampleTable(cbe_a); updateRegexEscapedExampleTable(cbe_b); cbe_a.table.style.marginTop = "-" + cbe_bg.table.clientHeight + "px"; cbe_b.table.style.marginTop = "-" + cbe_bg.table.clientHeight + "px"; cbe_a.table.className += " transparentBackground"; cbe_b.table.className += " transparentBackground"; updateExamplesTable(); addEventListener("resize", handleResize, false); for(x = 0, eArray = document.getElementsByClassName("regex"); x < eArray.length; x++) { if(eArray[x].className.search(utils.regex.doNotEscape) === -1) { eArray[x].addEventListener('copy', function(event) { copySelectionToClipboard(this, event); }, false); } } for(x = 0, eArray = document.getElementsByClassName("copyAsRegex"); x < eArray.length; x++) { if(eArray[x].className.search(utils.regex.doNotEscape) === -1) { eArray[x].addEventListener('copy', function(event) { copySelectionToClipboard(this, event); }, false); } } ui.state.regexTable.readyForTransitions = true; window.onscroll = function() { if(ui.state.copyToClipboardHUD.displayed === true) { window.clearTimeout(ui.state.copyToClipboardHUD.timeout); ui.state.copyToClipboardHUD.timeout = null; removeClassFromElement("copyToClipboardHUDAnimate", ui.e.copyToClipboardHUD); window.setTimeout(function() { ui.state.copyToClipboardHUD.ending = false; ui.state.copyToClipboardHUD.displayed = false; ui.e.copyToClipboardHUD.style.display = "none"; ui.e.copyToClipboardHUD.style.top = ""; ui.e.copyToClipboardHUD.style.left = ""; ui.e.copyToClipboardHUD.style.width = ""; }, 1); } } handleResize(); delete initEnhancedCopyToClipboard; } if((utils.browserInfo.safari === true) && (utils.browserInfo.safariVersion >= 3) && (navigator.userAgent.search(/iphone|ipod/i) === -1)) { addEventListener("load", initEnhancedCopyToClipboard, false); } </script> <title>RegexKitLite</title> </head> <body> <div class="printPageBreakAfter titlePage"> <h1 id="RegexKitLiteGuide"><span class="rkl">RegexKit<i>Lite</i></span></h1> <span class="frameworkabstract">Lightweight <span class="hardNobr">Objective-C</span> Regular Expressions for <span class="hardNobr">Mac OS X</span> using the ICU Library</span> <div class="printOnly dateAndRevision">2010-04-18, v4.0</div> </div> <div class="printPageBreakAfter"> <h2 id="Introduction">Introduction to <span class="rkl">RegexKit<i>Lite</i></span></h2> <p>This document introduces <span class="rkl">RegexKit<i>Lite</i></span> for <span class="hardNobr">Mac OS X</span>. <span class="rkl">RegexKit<i>Lite</i></span> enables easy access to regular expressions by providing a number of additions to the standard <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html" class="section-link">Foundation</a> <span class="code">NSString</span> class. <span class="rkl">RegexKit<i>Lite</i></span> acts as a bridge between the <span class="code">NSString</span> class and the regular expression engine in the <a href="http://site.icu-project.org/" class="section-link NBSP_printURL">International Components for Unicode</a>, or <span class="new-term">ICU</span>, dynamic shared library that is shipped with <span class="hardNobr">Mac OS X</span>.</p> <h3 id="Introduction_Highlights">Highlights</h3> <ul class="square highlights"> <li>Uses the regular expression engine from the ICU library which is shipped with <span class="hardNobr">Mac OS X.</span></li> <li>Automatically caches compiled regular expressions.</li> <li>Uses direct access to a strings <span class="code hardNobr">UTF-16</span> buffer if it is available.</li> <li>Caches the <span class="hardNobr code">UTF-16</span> conversion that is required by the ICU library when direct access to a strings <span class="hardNobr code">UTF-16</span> buffer is unavailable.</li> <li>Small size makes it ideal for use in iPhone applications.</li> <li>Multithreading safe.</li> <li><span class="hardNobr">64-bit</span> support.</li> <li>Custom DTrace probe points.</li> <li>Support for <span class="hardNobr">Mac OS X 10.5</span> Garbage Collection.</li> <li>Support for the Blocks language extension.</li> <li>Uses <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> for greater speed.</li> <li>Very easy to use, all functionality is provided by a category extension to the <span class="code">NSString</span> class.</li> <li>Consists of two files, a header and the <span class="hardNobr">Objective-C</span> source.</li> <li>Xcode 3 integrated <a href="#NSString_RegexKitLiteAdditions__Xcode3IntegratedDocumentation">documentation available</a>.</li> <li>Distributed under the terms of the <a href="#LicenseInformation" class="hardNobr section-link">BSD License</a>.</li> </ul> <h3>Who Should Read This Document</h3> <p>This document is intended for readers who would like to be able to use regular expressions in their <span class="hardNobr">Objective-C</span> applications, whether those applications are for the <span class="hardNobr">Mac OS X</span> desktop, or for the iPhone.</p> <p>This document, and <span class="rkl">RegexKit<i>Lite</i></span>, is also intended for anyone who has the need to search and manipulate <span class="code">NSString</span> objects. If you've ever used the <span class="code">NSScanner</span>, <span class="code">NSCharacterSet</span>, and <span class="code">NSPredicate</span> classes, or any of the the <span class="code">NSString</span> <span class="code">rangeOf&hellip;</span> methods, <span class="rkl">RegexKit<i>Lite</i></span> is for you.</p> <p>Regular expressions are a powerful way to search, match and extract, and manipulate strings. <span class="rkl">RegexKit<i>Lite</i></span> can perform many of the same operations that <span class="code">NSScanner</span>, <span class="code">NSCharacterSet</span>, and <span class="code">NSPredicate</span> perform, and usually do it with far fewer lines of code. As an example, <a href="#RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles_ParsingCSVData" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> Cookbook - Parsing CSV Data</a> contains an example that is just over a dozen lines, but is a full featured CSV, or Comma Separated Value, parser that takes a CSV input and turns it in to a <span class="code">NSArray</span> of <span class="code">NSArray</span>s.</p> <h3>Organization of This Document</h3> <p>This document follows the conventions and styles used by Apples documentation and is divided in to two main parts:</p> <ul class="square highlights"> <li>The <i>Class Reference</i> part, <a href="#RegexKitLiteNSStringAdditionsReference"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code">NSString</span> Additions Reference</a>.</li> <li>The <i>Programming Guide</i> part, which consists of the following chapters:</li> <li style="list-style-type: none"><ul class="square highlights" style="list-style-type: circle;"> <li><a href="#RegexKitLiteOverview"><span class="rkl">RegexKit<i>Lite</i></span> Overview</a></li> <li><a href="#UsingRegexKitLite">Using <span class="rkl">RegexKit<i>Lite</i></span></a></li> <li><a href="#ICUSyntax">ICU Syntax</a></li> <li><a href="#RegexKitLiteCookbook"><span class="rkl">RegexKit<i>Lite</i></span> Cookbook</a></li> <li><a href="#AddingRegexKitLitetoyourProject">Adding <span class="rkl">RegexKit<i>Lite</i></span> to your Project</a></li> </ul></li> </ul> <p>Additional information can be found in the following sections:</p> <ul class="square highlights"> <li><a href="#ReleaseInformation">Release Information</a>, which contains the <a href="#ReleaseInformation_40">Release Notes for <span class="rkl">RegexKit<i>Lite</i></span> 4.0</a></li> <!-- <li><a href="#Epilogue" class="section-link">Epilogue</a> --> <li><a href="#LicenseInformation">License Information</a>, which contains the <span class="rkl">RegexKit<i>Lite</i></span> <i>BSD License</i>.</li> </ul> <h3 id="Introduction_SupportingRegexKitLitethroughFinancialDonations">Supporting <span class="rkl">RegexKit<i>Lite</i></span> through Financial Donations</h3> <p>A significant amount of time and effort has gone in to the development of <span class="rkl">RegexKit<i>Lite</i></span>. Even though it is distributed under the terms of the <a href="#LicenseInformation" class="hardNobr section-link">BSD License</a>, you are encouraged to contribute financially if you are using <span class="rkl">RegexKit<i>Lite</i></span> in a profitable commercial application. Should you decide to contribute to <span class="rkl">RegexKit<i>Lite</i></span>, please keep the following in mind:</p> <div class="table" style="margin-top: -1em; margin-bottom: -1em;"> <div class="row"> <div class="cell"> <ul class="square highlights"> <li>What it would have cost you in terms of hours, or consultant fees, to develop similar functionality.</li> <li>The Ohloh.net metrics do not factor in the cost of writing documentation, which is where most of the effort is spent.</li> <li>The target audience for <span class="rkl">RegexKit<i>Lite</i></span> is very small, so there are relatively few units &quot;sold&quot;.</li> </ul> <p>You can contribute by visiting SourceForge.net&#39;s <a href="http://sourceforge.net/donate/index.php?group_id=204582" class="printURL">donation page for <span class="rkl">RegexKit<i>Lite</i></span></a>.</p> </div> <div class="cell" style="vertical-align: bottom;"> <div style="margin-left: 4ex;"> <div class="centerHack"><div style="margin-bottom: 0.75em;"><a href="http://www.ohloh.net/p/RegexKitLite"><img class="noBorder screenOnly" width="100" height="16" alt="Metrics by Ohloh.net" src="data:image/gif;base64,R0lGODlhZAAQAPMAAAABABUXFR8gHiwtKzI1NWhHKUNEQk5QTmxrapdXHO5xCJlyTIuOjaaopM/Pyvz++iH5BAAsAQAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAAZAAQAAAE/hCxSVlrlaHAu/9gKI5kaYLGoa6HsrCHMcx0bd94ru98fxPAhEKRIBCHRaByyWw6n9CodCoVGgxHojB57Xq/4LB4TC6bw8FkYksoEIGwuArxqD8a8rycrnI4DnwHDIAPLIGDenppaW9uSYkrdAgSDwiQiXx+kYSchp2XMEEKV0dFjkBndFeBDg9/CK0NDymtf7IHd3S3q7O1ql2qtQfCZ0pCb41vVAS4dg0EFwYODdMHstAN0tm1KXUOBnAPzOK4S+Xl0dPLBJMEBtmCGAjr4yoM4q3eheME+a4E9+bh0hWOXzkl5/DZcbCu3TsDGtgxUOID1wyLF9jByiZrQMZ2iX4YWpQ0wGLCFeNKivuIwAcQhxyVZAPiw8CDGQTESXNF687Nnd+uPWBgc8a9KzdzZrMzq6hSoDJ6vJyHICaQmQROmGjQ8p7Wr2BHTK2aLaIEJWFF0HG1Ia1bsHAuVE1hYZASAHjz6t3Lt6/fv4ADC+Zrgx2BHIMTK17M+K+AD1lDCGhMubJlvhEAACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter+wr3gMvqrMZW+MzPYGk4ktoUAEwu6rCgLP5zNUGoAqewd/LIaEfXxvb3V0SYorCA8OlQ6RkZMHCA4Nm5cInpqSoJ6Yd0EKV0dFj0BtXZMIsw+Ds7YSKbN7EoW0nJ4pDQYMD7Rqw8W8t7BXSkJ1jnVUBAfGEg8GnJUSnQ0PBNsOtMrW3wd24N9/4ErWBOviCNTh8wbDhRjz9OYNlfDjOjlgQExdwAYEHDxAaI1bumrg3rmLaBAYvVkE7hGbJ0GJD4mykwZY6mRM2wORlhB+Y1jLHzprA95Z6wIxJriRDXwAwagRIZBhQHwYODlg6AALvS6EOonUkMAYJw0MLHqSQK2huzJWrdX0gM564Yb5hGcAyAl4HAbkJGCBQdgLDwKwxRBW7bwGHEL9DKDW7YULe/vOdXu2XqhkHN2aPVFiggS8jCNLFmFHKb626IAA2My5s+fPnYnRBU26tOnTpW2EI5ADtevXsGO/FvCBgAgBsnPr3m06AgAh+QQABQAAACwAAAAAZAAQAAAE/hCxSVlrlaHAu/fDJ45kEJbcia6fcbzwoSzxYQx4ruvE7v/AQS+IGxKPO4IyoVAkCM7mU0mtWpUHpcFw7XqxWiqXMM5Wx+OvmrmNOpnTrXw+PyBgCBdMv49t+3d7BnkvLnlzhDZ+dIxbS1MJcAQFTlg1ly8ImpqZdjWBd6Cenpydo4F4pqGYmI+PlZRTrJcam52hoqSZpQx2qLm9MbmrszFLCm2SsVqNdAe1EoakuNKgvL6KDC7B2nLP27c2zXNUTJWwlWpVBw2b2py4vgTwNpsuDXa9BM/7+Oxy+xj0w3ZHXRVNZBpsw4DA4DoHmxrMWwVPIL1Bmlw4yJfFgMR//gccnPmokJ5DJQg9GtAwT6ASJANCbhIpwZMGOw0G1CxIYd9GCwcGGHAQ04FGKkKJhhzU6w5MlA1VSlSi8CUSAw80MXigU0OvmwhySqhJAINErM/wJY35gEzbl0PZtqz5dOI8hVPLjmERAOsWBFwtjMXwzEEAwSwvnH3ATmEAAoYPtMXKI3JbxBtYQA2rkKUEKnwJvAUc4EJYBA6+Pijdrh1kB0RFpzXweLVkJVxx1A5w23S70P1aL9SnBIDx48iPD8gtGcCFARpSH37gPKcGALAdAFg+T+R26su/d/hO/vn15Oi382gIJD368ABEV9cZksH0+XewwyYv+QD58MvlL/Afdc/l5x5yAnxAAAkCHIgcfOFdAEAe0m1V3YQG6KddeLIN+J2AABLYAIYOHhcBACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC7/xxxaEQwBJoUEM4hGR47zGZjMiITuAgC9xuQEGQ4GI8HxQJ5MMye0OiTIPENCAOM5doiQVmE8LUxLjIGVcZhoDlL39IwIaFQJAj2+l3O7/vDIwiABA09DQQGhRoHfIlHiIeOCIeTE4IUf5l/dAYGeXZ0e52jpKWkEk0uBhVFhUCkB64+sa1GDattCCMTTaa+pWEJe8J2BAXFIkzKyqg8gc0NLotIsrbWsdKWu2rL3UjBw6HGyN7ePUe6QLojRudIKevc8jzuQOXlwQqdeXfHor8AjXRS5ayID4O9DNojOKvhOoQAIxqQQ6dYMX+aMmrcyLGjRz5yPSCZwSDoo8mTKE+GTLRKkAQ5cGLKnEmzps03YVbeOhTmlpibQIMKDZrT5U45PksMWcq0qdOnUEEUnXSLxMswUbNq3boV0IVJI9XIAUC2rNmzaNOqXcu2rVu0UahgefO2rt27eNcK+KAUhIC8gAMLRhsBACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC7/9wwEMTQkWQwIKNhdut3hOJb0y+of8bh/wfFAnhw1Y7II6F3KImAIwbhgDCKCAwka9BctrwDAylJJqMSCkWCoE6vUfC4fIqodwl1ydRxmNz3cAYNJAg+CHRUYnlzjHNoBgZtamhvkJaXmJYSF1VFFxdUDwiclwgPPz0OPQ11DAYSsH0TmbS0JAlvuGoEBbtTRMBEEg6sVAfEDXymDMSFP6ZACMoOm32fhZ/B2kS3uZS8vtvbowyGxxfKDxYa0aJ20KbDfcQO5cji4rcKkG1rvZW1Ao7qhC2bNHKFNFF7p0oaFVUX1h3IFrDiGTds/Plq1GiUmESvrDxOpMJKDImJeVZNGTQRC4aSFhqY5NjxkKAe6w7RrHnyUB6bUgxoCKShzpKgSPHkadJqJ0ejN4fqGVOmqg8Rr8LUcYHnyaEaSo12HcsCUQljVdOOULpE5iASMqmqnUu3rt27a416fEsgLoEdgAMLHky4sA5CdS4I9SklheHHkCNDPslJprVyKABo3sy5s+fPoEOLHk3aMxI8TpKUXs26tevQAj781SHgte3buD1HAAAh+QQAAQAAACwAAAAAZAAQAAAE/hCxSVlrlaHAu/9gKI5kaYLGoa6HsrCHMcx0bd94ru98fxPAhEKRIBCHRaByyWw6n9CodCoVGgxHojB57Xq/4LB4TC6bw8FkYksoEIGwuHxOr9vv+FU6/XYn84AHCA8qDg4sg4iEgYwqQQpXR0V+QGdeDg+ZDl0NmQ0GgwaGMV2hXYKWqWiPb31vVEwqgwxKDxqLD50HsQ9LB72/mA0EB5iHormwTwgIBAafBxYayk4XS53Jvw8OTb++wA8SvdYODb8In9RMzM6f0xJKPja/MjMGuCnh5fMPNb8D//5h0kSgEzd5NoCwe/ZMSToCCGkwcGCvWbhBzvqdq3Gvy4B7bB/7gbwwgJ25B/UiDlDYDF1DIA9PfHDAgMOgAAwy1bzHISeBDvcy9eJJ9EEAZAc7NRgg8wNLdO5a0gLStKrVq1fhXHAZDcMuIADCih1LtqzZs2jTql1bNmGzHGzjyp1LF60ApyIE1N3Lt2/ZCAAh+QQALAEAACwAAAAAZAAQAAAE/hCxSVlrlaHAu/9gKI5kaYLGoa6HsrCHMcx0bd94ru98fxPAhEKRIBCHRaByyWw6n9CodCoVGgxHojB57Xq/4LB4TC6bw8FkYksoEIGwuHzOQjxUDkf9vrLT/4BxaWlvbkmBMA4Pi3oqDYsNB355MH51iJh0QQpXR0WGQGdeknYMXQ8ad3aPMV52rg8GdooNKYp6BreiYEpCb4VvVE4XS48PDQQHjAZMykvOyhIPBBe5kQ8IkcJOCAgEBrUHFhrbTcoHSgaqsdHHzdNK0NPOiozUDw7lTd3fteQSSnzYYOBghiQC2OwkezDADoIa51QsHKCMIkNi/K4dEGgDCD9wa+CU1ALCkYYDBjMYMFSJaoC6lLFoqFsU66VNhrnwyXhUsCQNj96yhQQyksCJo0iTKh0BNJu/oAyULJ1KtSoIOBeEisOADgiAr2DDih1LtqzZs2jTju3oLYfat3DjyjUr4IPREALm6t3Ld2wEACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter/gsDeWInfNV7R4zf4Gk4ktoUAEwu74PIyh0uz/eoGCMG9vdXRJgzASEwgrjI4IDwcIDg0skpgOipx6QQpXR0WIQG1gDQ4ODw1dqKmUD5WXXpJjrAcaGikIvDG8CKZiSkJ1h3VUTH0OCEqWDJMHq5PJD0vRBNGuBJWpwKmsyE68BAa3FhrhTQYODEupqdgP3dTW1dG81aiyB+zg6UvjyhlAJ0GJDxuVCAzARiCWpHgHUB1QOCNal3gDomV8MOCdJQKJ2g7aABKQVQMl/kTSuFCxHTsGDshxXMeghgGHzG4O0KnTgoSJGGKqpEGSGQKTKA0AOfFBA4eIAY422ACSw1ECHUBeOFm1a4MABM4pPDeA6YeiUgcabbfUrNu3cN/auXA0xbmJQADo3cu3r9+/gAMLHkzY70hmOQorXsy4cWABZ0UIcEy5smW/EQAAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YNgNYkCWaJoaR+seyvIexmDfeK7vN8EPvp9wOCQYEwpFgqBMLo3QqHRKnR6MBqs0W+16vUiDoalEPsXotBo9Y7tYiFf6gFDXWSyaPE9b+9dHTwlmBAVKRjOJigiML4yNdHRxM5Muk5ctcZiVip0tgYGHhk+eno+OpwcMkomrjpmwkZeQpZ1HCmJNS6NYf3+ScXiPk6uNcwzHcJnKwY++z1wESIeih19UwH0GGhIsDXSrUQcNaASqBAaXBI3NjNHXU4zo5KoYCPDYEnHoBNwM5g7AXYFywEEUAw3QufrH7sojfFXkIdx2TwIUIjnSaRhIoAGjhPoF6x3AUfCiAQcDJqoaICHSOosYdRiRSC6hEXJGYt5I53HgAAwMDBp4IBLHUJMoO3pjqSGchoQ6ccysWBMKTgIqPqzzWMOHgwkPUhK9YMDDUKkOAhBwkC6tBX0/ETQ4kdXDVLnkNKz7Z6SuB7kjUw54wCgsAaIWynY4fEPtA8frHl+QiyAuSr92zU2mZyGcEQCgQ4seHVpuAABqAxBG8HjwOoOiB3cAMJj248MALgzQEODbY9LASedYF0RH8OMAEDgAnVK1mNYPABwgGjusDdvYa+uOE2DVb+TBBWgVIQA8cAvMD6huAR3A4QPVb2SPrr1B8rIMBg8wDzwCACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC79wjyhCQTDEQzcKsmBYRzSIanHTMRhPO2hwFDQ/cpegy4JE6xUB4Mg6h0OtU4JBQVweAgRL0YC0qm8Uo1BgMCygtFNYzBwQGl2qeEfEKhSBD6fH55g4SFeVYhEwhDSA0GeQcpIYwNEgiRgzczj4oTh54HDZiGpIN7aYB9e4Jpra6vEg4Zomm0mxWNJGutLjwGvQxIFDi0r8aueoIJqwQFfZBO0TiTnRNJoj0HLgzEM5rTJZfAOMOhl9LoycnPzoLo0ZO6PORJl7r02fX3PSTg5/PvnOhRgIpZuzzHjnn7d6lVw03ZkOya8aRVRIm+JFZsmPCYqUCGf/wcLFVKzSOSKFOqXKkyxBZH2jAgYEmzps2bJF0K+TVTwqA7QIMKHUq0qNE8Oh0NyeMoj9GnUKNKxUPA5SIhg5oSMcK1q9evYMOCRTrJURmfecSqXcu2rQdIF67G5DYIgN27ePPq3cu3r9+/gPVSqWrGTuDDiBMr7ivgw9YPAhZLnkxZbwQAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv3BIGEJMENJkgGA4IaA2iEMDvcsR0Px+f7hoNweFAsiAcYbsnkHRjIw03EJKIYhANCedMKR6jSbUZAgZvoaSihUCQI7va7RK+LEA6Efk8IMsghe1gHDk9QJRN6h0iBelkNgHaSbAYGcW5sc5WbnJ0XDxgXFl+FlUkXF1oPCBdbm6IWW3t6fhMGeK6duptrcwmZBAVuIVHFB5+oF4USq1+EyqoMDg0IRNN61McUDUKoT83Gxb29w8Jz4UifFqLLCODV0w3LDxYa1hoS1aKpz9wM4OiIrFFQKc4bczR26bIACpW0JAbyBNHnDReGaq/waTBw0UIQb8qEICrURYLNsHLDJNnR4yBWKDLcsmyhxuqjFmqAEkk4QIAmqz7rbKpU6Yijn4tDV+KaNSLEH5l3imIxoKGEFkUzmDaaeihpnaKQqkogkabJrWy3zrQoc2tAWhhUeKiVWW2KlzJypWSRUrZJoz6QGpCAFKJvExeGEytezDiMo5qCQxBO8eNHjsqYM2vezJlDI1ZhR4wN0bm06dOoVRyjBukJBp4hAMieTbu27du4c+vezds2ExF4m/QeTry48dwCPlD+IOC48+fQbUcAACH5BAABAAAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter/gsHhMLpvDwWRiSygQgbC4fE6v2+/4VTr9difzBwwPDIAsCA8qDg4wDQ8PDXmEhUEKV0dFfkBnBg6NioKDV4cIXo2PBoeci6UOEqFlqZtXSkJvfW9UQA+HgYOppgdLvogHj4hMu0AICAQIDg+tBJyPBM8OuUvL0g0pFhrYQKaQw8EEx0riBMXQTedKnQYN18UI3MXgStrxBt8SSj4zDEBzIOiZjAGIaAhU8SDFrk42ds3QgPDAgGIDCHhS9wAgDWWUzPY1QGcACMBFiB4t6zij4QBU5lZK60ivhrwDowZ00ugg47grLD2CbMZtZLiSBE4EADUI1AYODQMcWuqIQQCBHAQl5TDAFIMBAQ5YOxCg66OWDZRyAFmPWz8GStSa26q2rt26cC7U64ahHAEAgAMLHgzgL+HDiBMrXsw4sI1mBHI0nky5suXEAj7Q/SDgsufPoAlHAAAh+QQALAEAACwAAAAAZAAQAAAE/hCxSVlrlaHAu/9gKI5kaYLGoa6HsrCHMcx0bd94ru98fxPAhEKRIBCHRaByyWw6n9CodCoVGgxHojB57Xq/4LB4TC6bw8FkYksoEIGwOIvxYMjvLMRD5XDAGg8PDXgwdoRxaWlvbkmHK30PfXR1KnoILICCB3oHfX8OEpSHnI4sQQpXR0WMQGcGD5x0GnuZCF51nHqAMbe2Bgi2CA6RvsMOBsauV0pCb4tvVECZg7h7QNZK0wQHgcdMsEwOgw0O27CD3NFMwAQGDSkWGupK3JKR2Njte3opsILfCIDIs5aOAKByBecRYOfOgDwJSnwMAOWvAbAHBGbsGbCJACw9i+YGWKpB7iKCiQ0MOhhgkJsKjBJnAGH4LqU0A0AkTqoz6aRGGXQGTGIw4NUMOjJoZCLK0diBGQdZCorJcmFABDWz4SRwgoNHrl3Dih3bYSawCw6vMlAi1gDZt3BJwLmAFR6GA0oA6N3Lt6/fv4ADCx5M2K+NhRlxFF7MuLHjwAI+gAUh4LHly5j9RgAAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcslsOp/QqHQqFRoMR6Iwee16v9cYeDwWq74ssnr9DSYTW0KBCITZWRLEfQ9jqDQwEoB8eIR3bm50c0mGKxYPGIJ6BxKBE3oID5QODXgOnw2ThAidjSxBCldHRYtAbF2ckBeglAwPCF4Nnw6Ut5xiV5wICA64lMNiw7i2uK9dSkJ0inRUQLESDxqajwdLnLYqkJpMt0B6BAycDgwEBqAGDdnVS8PtDSkWGvNA6ZDpGOMIBLS2i8CBB58QkFNosNs6A+kMrrt3cJ+SevAgKpSgxMcAPbSQ1sUiMEPTAIMChz0wqElXNxoPD4QaUC7TSV0OWJL0eJIAxnsNlNwD4hFgOgoNaDyQcYDduogGHgxwx6AGsQm8BlwglZQAhpwCD/DsWY8UPKEGgJwIQArSsAsHOgQNIJPt1gBeOZAi0OHj1gF48/EdkG8GhrUczL29p4+j2rVaASOeTJlyna0U83UDAqCz58+gAQQITbq06dOoU3+24XPnDdWwY8uebVrAB74hBNDezbt36AgAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/wQCOpEieaAoaR+seyvIexmDfeD4Qeu/zvqBwqCMYEwpFgqBMLo3QqDR6mEINVqoRm+1OuV4r0mBoKpFPsnrNbiFmNFZc/WK9XWu4HL+Xs/9/R08JaAQFSkZwigcIjY6OLneRkIyMkm6Pi5V3l5ovgoKIh0+eL40aj5KdmQcMljOpmK+WnKVwRwpkTUujW4B/p6kIcq5kNKyujXMGscxvjWSOLMW/gFBIiKKIYVGNDakMxq4EaqjhBw2M41CxBMqN5NLoVdxS8AYN0xgI9VEaDhIcMSCHjgsWcwQOOFBHz8iEU1Xe8XMHr2C/bvzwGdDgbqARIv42/klA1SBRvh1GviEoqbBVOhz7Vh4YoEHdjlMJHdQAacPIvXwlU3Lh+e3BSgoOdiis8REDAwfkHriceeOCt5k1JezQwPIBEJ4++a3EByWfERUciq50mjSqgRA8HEx4MMCA1AtvOzhgmS4ABpchvjUYcMAr2g5h124U65HAYbV7G9HdYbjuAKMI6BKQaiEvh73k+spt5SAwgqSFHR8OYFKwvnUEAMieTZt2OqlyJQeQTRcA6wCYH4Twejr27At18wGQG+Cp79vDa0uXnsPd1xzTp5eU+iDZg9m96wInI/wygMIHbLNcuJxBcwe+XZX/nj27gA+qQQioXxuq1+7M0BwHQHgHANfCfABslt5sTyUkVXvvxXeZDQLyR1sEACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocC79wPRDB7hHIcUpAhiEC5CsK4ZtGwwNDltDAwC6UP0GFBIlGKRPPwG0Kg0SjA4hNSrATGSSJyMA2OrCZsGuFbopPaaG6+pfEqoJxSKBCGP19f/gIF1R3CABjwpQVwTCGJfixqHBIwTMw4SihiRPC+CnoB3BgZ8eXd+oqipqqKcqAcNLRIGlI1lYmWNcBotYweXsrSvTqvEqHZ+CaYEBXl1Tc9NiEmwsYmMt2GYGsK7j7/ZFLnQ40jHx83MfuTQYU3djbGNNDTy2fEo1PDVYuvjdgqi+OhJN6gYsUap5oligeIIQoYoXCjk9xBHRIMG/9xphq7Zp4+AIEOKNCRjpMk/LarAEYOh5MmXMD0diDky5aFZMiT8mcOzp8+fQIMKrWMTToM/hbAIXcq0qVMoRHMaRdqpiNWrWLNq3co1KhddOYPU4Uq2rNmzJWZc4HLEgpk6AOLKnUu3rt27ePPq3VuXjgyefAMLHkwYr4APBKwKKMy4seO6EQAAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/AwEiBGGIwaCmQ8qp7bDBK1vDb/vtn3H8wINiETwYaMgkAYEkMH4IpskUOp6mR2eoVFIduFXq4Jss07gJhSJBWKvZ3Lg87mNcSwdHdEI4IPw+JH9+gHl9QSWDX4QIJ393c5ElaQYGbmtpcJWbnJ1+DkabCA8TFwYSqBIHGqisD6dRUT4Ne6caGge0oZ28m5NwCZkEBWt4RcdQDA+KfssIDaAWF1G0tNK0o7kUDZ/SqxfYeszIRb+/xcRw5MdRy0Gje9EO0Bp6egzzDhoPuRgXzd7w0YM3bt2PSQoquWGTrkSvhwb0cEIgzoKBCxae+OuXkeLFW8oNTi2ziBEDxUcQeaF504ZhMUkwucXJtYeBE3+NMhrIqKsBAWzP+jjzyfOPT5hIo5gI+U0DUph26LB6siTWF1RVoxixGUtpnlhZH9l8KknpxZ2CxhIwY4bEGatr+/xZeyouoUQh7g646Mfu3CVs2SYicfbozyuBEyteXEYLY8aDl4Q0HLIEj8uYM2u+PGazZw+Dn4V0KoHL59OoU6sG3Wca04xfSgCYTbu27du4c+vezbv37SZuy/geTry4cd0CPqDYIeC48+fQb0cAACH5BAABAAAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter/gsHhMLpvDwWRiSygQgbC4fE6v2+/4VTr9difzcwgPgw6AKoKGiTBBCldHRX5AZ1eCCF6VCA4Nk5QPnJ9ojG99b1RADYMHSwcPQIIEBw4PhZoEF7GzKq2Zswiwsw++uIWsF6ZLCL4GmwcWGsdLD6pKrHCtxpoMrcHYDdWayw6/EuLdrAzT0MkEywbPEko+NNI1rDOCA7KEBMGt+rkPBtCzV83ev0Kt5NFwpWxTAyWbgCgUKIOGAU+xGgy4MCDZxgd1Gjkmu5jvYQMHAy6S26hxZMCJAxgSQOAQogEgJzp48nBxXwADssQFqPQzKLsHAYYd+AlsA9BZR3N6YEhz0zsGSqRq3fqBH9cScC7QTOEsHYCzaNOqXcu2rdu2+d7KhVtjJoEcc/Pq3ctXr4CuIgT0HUy48NsIACH5BAAsAQAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter/gsHhMLpvDwWRiSygQgbC4nIV42B2I+byu7/vnaWlvbkl/K3V5hw8ICA4NhoqQknpBCldHRYRAZwYNdghedVeiBw4PDqUNnaimqKKNp6B1pgwprQd1F5xXSkJvg29USw8HSwcPQHUEuo4MDwaLzI/IjgcNDgTHCNfLqtUPj8JLjASdKRYa4sPFSsfJ1Han0Mqmd+7E2cju7vWn7upKyJlLJ0GJDxrEahxT4WjABQKMHIJz2ABingcDHC1zMEAbA453DxkdO1gjGYJyqioCUQWE5IBnNaDdITDAQCsZiGrehNbxVs1Ti3TK4+lygEmIKZWwJHCiqdMS0J6eMLlNFUEGSqRq1UrAwVYScC5sO4eBHQEAaNOqXcu2rdu3cOPKZWsDIk0cc/Pq3cv3rYAPTEMI6Eu4sGG2EQAAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcslsOp/QqHQqFRoMR6Iwee16v+AuK0wWl89ocjCZ2BIKRCBsTodREPX8gaHv+2Fra3FwSX8qEjAIDw6MfIYHio+SdEEKV0dFhEBpVxIPCF6RCA0OKQinkKCop3iKpqgpGqeveHuznFdKQnGDcVRAFg8HSwcPQIoECIwOo6UODcqMeMYMzw4MBMWkDcnL0xi/S6cEBg2xGAjhS8LExsnGpMrQwp/xz8UE1wbV2Z8M8MzufRqmLlm6cvvSSVDig4awGsWuVBuw7Fk+UvmWNSg24NO7AZbFID2gqJFjQxrHDprjBsQckJMdZdAw4O/aAAuIBpBicBMaH5o6oV0YQNNCg56IgMIckDLZSiUuCZzowM0DgQsYBgQgYAFbgAMbt3ZtKRZcgKJhuYK7OtWqwVHmNCTDBqSt3bsf8uEtIefCqHN8lAAYTLiw4cOIEytOHIDB4seJbSQjkAOy5cuYM18WkFeEAM2gQ4teHAEAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/IDeEJDiWaBoaR+seyvIexmDfeK7bxO7rvZ9wuCMYEwpFgqBMLo3QqDRqmB6M1ak2et16v2AC0mBoKpFPsnrNZtHWB8TL3XKz6LQ4/j2f39uAa0dPCWgEBUpGM4szco0IkI5yknEtk5aMlZqXmpmZg4OJiE+ejI4vGpGYlKwtDHGTrK2dpTNHCmRNS6NYgWyub2QHqZAsnMeaDAaQsMbNlZTBvoK3iaKJYVAsr1wNsAwEzK3iLQ3hsQTLsOeV6lnZUJDpDdsYCPDaB/RcDnET7OM4OQB4z8AreeQM0sAXryA9DeHAGSHCQ1+NGwf6SWgwQEIyCf7LDrZwMECDvwEGvEnoKDLlFYo3jMhLmRLKviBECGS8aMPAg3IcJXg0CFLoK58lJzEYQKABpKVGr+yDyeNcOHrmjNxUwSHdAwMefGp1EMCC0JQIHjrV4DMAhmENAhBwsLHs2nsOqnDtIBPSBaIRoexl+oCABwIPmDIgeyEtAgMOFjd16hRxgMjDyCKWwJjyva+G98rV2ZgeXG5GAKhezbo1gMSsBzwIULIBgAtJL19wy1GDbACRyzoAIDvOcNy+Z7teHhtHOJw5mDOHvVq2jQu3gx647cA2bjm/gy8m/hXBce2/pTMX8CE0CAHqXVNXbX2ud9uPud8H8Dg8A+HkGQqXHX81PBDfchEAACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocADcZrkBAdiGkZDDMw6NAFyzJy5dd+8ETJCdBodw+MgHIafWG9XPHYMs+hMsZAeDIPs4GOaOAYSycxhIDTKZrAtq2Fot46S+yjBshEoRAMOdX/UJQh8R1oEhgkKCgkEiomLhpAEKRIaKnoTMg1XmigqmC0EFJGTekYYDAeQQSUqKaySnm0trqWRiCiNioiPKCgHDZR6Bp+ZM5y/w10zFFe+wHrGE83JNqi/xlBnIXXXyCiHjwm7BAWKhlaamJqUQcDd19vL0lLP1hfWOjYmxvzw1f2aZoADZ67cIyuo9iW0ke9IlIX7AsmQEu+IOyn6JlrbKDEiR4G4BG4ZaLTIoKFeUPBMxBNohoGVvljuizktZYkrcmqmlBEzpU+JOGX2goTIXEFzkZIqXcq0KdOXPpxKnQrJBKw+GKJS3cpV6ZWuYCNZTZGMBygXb9KqXcu2rdu3cN0aGntGhaEzhuLq3cu3b9u5PoTZNYOmg+HDiBMrXsy4sePFgPVoC3z2seXLmDNDNgXsjEVUkACIHk26tOnTqFOrXs3adFoeaNO2nk27tu3UAg7/SCzgtu/fwE1HAAAh+QQABQAAACwAAAAAZAAQAAAE/hCxSVlrlaHAw0DHMBybJ3oHdwapuLqdh8DnGhAGoROy2bu1jc1wKBoPisXxYAASNLjJAIebIggj7Ge6E+W0ome3mnORioiZuPrkjhm6ZliXUCgShLsdv9sdHA0kDQ4EZwhEDTkgBgYNhUY6aVd+DmiFVyA7EpJwf5Z/j5CeJH0EdYx6d3V8jIwIDw4SDg8GmxoIsQcNIH+1kkUUrbUPaQy1DAcarRcTFyTEEsO+ksPFrXR8CasEBXc6R68YFw/JF7sM0LFplRgTRebgD82CCLtGgMWVrxKBr7oU/YhZgGQq27ZufOJZGJcMkIMJ0KD5YxbojzMjryxUYvAwV5GH/pL0CRSpS1xAWQRPGdCDB2GcVrjq7XLQSBwyfblwNdJQER5MdTidLbtVjwTOWjQx8ENq9BqdPXlaeiulq6SuJ+JA9PzmaFcaRgu/FPKaqKYxTbcmIBrL1ms9tlf7pMGRqByUUlGeGIMjaREyA3Dy9o0koQ9gSTo4TvrW90BewIIHQ4Ys90qjwwQK63Ayo0jmKWe+OZ5hBTQIEWc4k2iSORGQEWkcl/5MO/Rs0lzmXnakI9Hm18CDCx9OPDNu4siRE27daIdvHjGiS59Ovbr0LNaza+dAWCZmzdC3ix9Pvvx0rrvqWkC2A4D79/Djy59Pv779+/jlv84M5nX+/wAGEShgfQJEF150Agyo4IIMyhcBACH5BAABAAAALAAAAABkABAAAAT+ELFJWWuVocC7/2AojmRpgsahroeysIcxzHRt33iu73x/E8CEQpEgEIdFoHLJbDqf0Kh0KhUaDEeiMHnter/gsHhMLpvDwWRiSygQgbC4fE6v2+/4VTr9didZCA8OKg8PcgwwgXmKdw2FgweMKpKAhjBBCldHRX5AXoGGoGCBX5FnBqRljhoODagPn7Cjsl5KQm99b0wHghIODwQHv4PDvBe8BKANBAa/y0q8vwwErQQNDkoP08mw0Q/LyAjDCMGC30wI5AauBxYaTsYWjtbLrci8iMgOiJYPCK7Q/DEANpCAv2wHEPKSAEyfq2vlGKJT5+qdBCU1FjpwEGjAr0fFvAYgE/lggCEa1gQRoIHMYEJ/wGj4m3GvZMiQJ2/aLDkDSDpmD5UAXEnDALBCIS8MSGd0QFOnJfcJM2CNl4wZRtPxdNSgxsB0raCKbVrt2lieA3yS+7dOKFUCHowGECS3mUqTrh5wkMvr2wyuAzoY/bUhQKDCHAY48hugrl6+xRo/1stB7b+Ka7fBPcG5s4eQnkMHgHOBbTsMCYEAWM26tevXsGPLBmAQwezbuFfbSEb0Ru7fwIMLly3gw2YQAoYrX878dQQAIfkEACwBAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcslsOp/QqHQqFRoMR6Iwee16v+CweEwum8PBZGJLKBCBLMTDoXo8YCoGTI7vH/h+LA12dH93K4B7hyxpaW9uSXF2houIlSoIgYqaKoMaDnSJhn2iKkEKV0dFkEBecg4SDg8psnS1chdyBnIPDVe1rnMPDAYOvg0OXcNXfK+9u7MIt9CyvldKQm+Pb0wHvReDBBfFDd4E3uXmDhoPme3lSt4Tswyz7Ur3BAaH7fXnDwSMHUD2TwLAJQgQ6PN1wIIGJ96kwQIoi5A5c/8I3FkyyMESjL139vnDpzDjRYDmNp7MiFChAV8PJSip4W3fnQcDLhBIeHKGtwHrDtAR5+0AjYhyCOTsVaNeQmMDfkrFaUycg6g4f84AknDhSyW+gNTYN2AO2WJmNfrCOYAsrwYzOo4VhmCGnLo1BvVSehYnWaFzjPalwVUhgmNgDQA5wbixB6wDHEsOUPgwTMMMlEzePEIe58ZwcjF0eEAJgNOoU6tezbq169ewY6+2sVMpDtm4c+ve7VrABwIiBPAeTrz46ggAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcslsOp/QqHQqFRoMR6Iwee2qrt+ueJwim8HnMcurPsfGwWRiSygQgbCJSg87IPoMfYJ7gzASGiuBLIqAfXFxd3ZJLAgPDn4PD30IDYaXhZSaoH4OpQ5/laGCqTBBCldHRZJAYpUPCLYpuH8Mtwcafw0GuwhXu7W3uMPFylcNp5yXlRLMD7q4MdMaXUpCd5F3TAeWFg4PBAimnA+BDxjjBAylwgbzBkrjz8LP9Q1Kt3hEuStFAJ68ZwwKDnTABBcBA8J+YUDgZFy5XgSepet0btwfePHsDnQ64MDCvYC4rKUCCITlOBXJOp4raUCewpQNKUKsSVGCkhoeS1UaYMoBR4Uzxg24NQzIM4Y0Xo67ZxTqjJJ7GCrd+mBpz65caQBxuNOf05M1DMx0oHaABQkHCGhqO6DthXRObdJQO8HBjAbsaqTry6Bu17Z2G3BqYLjxjLE99ykRBsRDxgAYLsfLPCBzAw6XISqeYaFwh4wWDgQYkMoD67sDAmj+rLk0Adm0P4NGh+sCT3QJK58YTryDWwfFk+8WqThi6bhAAEifTr269evYswPofEC79+/SbaAjkAO8+fPo02cX8OF2CAHq48ufbz0CACH5BAAFAAAALAAAAABkABAAAAT+ELFJWWuVocD56MEHjmRZimYajihLGkcsH8oyH8ag68Q+9L6gcDgEEo+/oFEpJDgTCkWCII1OnVgnzgnLYg1eAjhMJhzK3nH2vC6zw1CDoSqFXuXyA2KGgMn8eXh9M3kxeDB7hoqHNzh6gI83iIByT1cJdgQFUlp8ewigMZ+ipKSJMqN8pamioK6rpY2Jp5aWnJtXNxquDKawvnqtpzG9wcHDrq8HxYm9oaHLsU8KclVTuFx4y8kMiMbMMt3POK6MzN57gsmD58sGz+yieFhQnLecXgcYoBYE4/rkHDHw90lOOSwAI43Csq5bQgRmGhDUA/GhF1BiGsCwoIHMAQf+uxg4mJhIo4FeciQ+c+JqjQOKZhY6mcDLzMtlNklWvDkwC0YDGjtKwOLjo4YJDgZIMOYg5RkDSTXoYTl0x0c9A7d120FTgsSPGwd8HCBVgtimy3ZQzQgUi0YnPgw8mHDhgdKjMR44eQuV7J6eGiTukAuqgdijOXRcKGxYLozGdssyGOBYn1qC/jRK3DsGhFwLGB4EsCBhj14CTZ04CNBgj+DWhjsQRpAUqAUDHS7IEUn5wbvVcln3shDAMe0OVBHoFtqTAAgCD2g7QCB6cesDp307EQ1SX4/WSZFHp00Z5Mjcb3lD9ycaeoDuIgOsp448IuyNGN4A2A9ggF4HTT2JAMAFfvnXn2gHAjDdALE1gF0A/PmXFwcOXADhfhf0INKB8gloIEijOcAhdBH64M8SPvB3oH96CUjgHgYamOCCsfWC4H4SPjhghSqKBMYFCcYoIIgbCsmfACM4V4IAKvoXwAN2udgAAH0YOSMCA4Q3mV0RPqCHgAM+MCV/tOHAo5EfMhBikGACEAEAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLvvhIOMTXCMiDGe5TkaBDqEJ2MEQ2k0RDj8OB3PlfoYOYaDcnlQLJgHw29KpYYMqsZAIjlMSFsN40AQ9xxeBGGmPThgjt6a0H5zx9X8T55QKBIEf36AcoWGcjtKCDyLX45xjRoHGA1RDVxkOwSTlksEmpyRaoekBH1Ygn99hFitrq6TKA0Gjo0Sb7VeE0qXKEmznLEvk7+6XK/IWD0JhMx/BAXPm1DUvIqVEl8YEtgUIxTWmMGXwgjWwt7V1MvNq9DS6tRjSmMo5hXYKIorXvv0/hr4zbPHL54nUwpQuYvGKtmrE1hO+KvxLUnBFOYgWlSEJaM9jo0qJjp8xWdQIEAMS6lcKXHEypcwY650uSOJBQ0yZSZRAiOnz5+kaM7CKUGOnqNIkypdyrRpD6Gaeszq0bSq1atYrcRQsygqnZ5HwoodS7as2bNPSQzlykDO2bdw48r10GPSJWA3yfQAwLev37+AAwseTLiwYcBVYqzRc7ix48eQBwv4QCCsgMiYM2sGHAEAIfkEAAUAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcskEIp7PpnTqdCKqhANWec1Sv0GFwXAkCpPjtFqNeDjejthqzKKrUnJD+4BwNFIOKQ18D2oHgQeDeDFrjWNBSQlnBAVEQDCYKm1PDA8IfBqgGgyaoRKnm36ag51PDywIrJ6gn5mYkJCWlUm2MG0UrwxwEm8NwcOdyW0Os4SJDw17K3vGGMO9LGFjR0W7QI6Ny3AGb8INqsbkDuaHbnpuDp/v821shfXlfuBrSkKWupbAKDnwihABZsVmtTkI70+1FK/OaSGYpRDBORQJkmsokMsVA6t/DljQ0HHgg0snLZy6YCFltFB+4mT0U7HipwcUINpUSbJkFJAGSEpQ4gPkDAINCIDEQKDPhQcDljJomjSa0QGxxjQYgJTB0gtauWKQSsCHFaUOlfwB4qPHhFhb28qdm+Ns1qRA1hI4YSLRhQN8AwseYQVu0CtDgQxezLgxiUsXsorEoAUIgMuYM2vezLmz58+gQ2+20bQsDtGoU6te7VnAh70hBLCeTbv25ggAIfkEAAEAAAAsAAAAAGQAEAAABP4QsUlZa5WhwLv/YCiOZGmCxqGuh7KwhzHMdG3feK7vfH8TwIRCkSAQh0WgcslsOp/QqHQqFRoMR6Iwee16v+CweEwum8PBZGJLKBCBsLh8Tq/b7/hVOv12J/EID4IPDXlzgSoODgeIBwyMDyyNj4Z6BFZYbH5AZ4EIn5FnYoEGijGMBqSkXairol1KQm99b1QEBw9wkQcOD4sIvQ25vL4HwriPhJG6BL2LuUq4zcXOB7YEnwQGDSkWGte3g4QEF80NDoXC5A3mzYrhvtHD80vS0uXo19nbBt8SSj5wXQk0oJegXgcG4Co4yMEABg8QKIyIbsbCiw9qYGR40AeQfZfc2AHhBsSHgYwDTg64MOBTPmErG7SUqMihSlwSVep80CVlRpUsP3nEhgBbSCUkCZw4yYFArlLxiAkLANUBAYhOGTANgJXpAEInB2l7EOArN2dKTXz8dKFf0X9ATphosCGQ3Lt4R8C5gICbIwzWgAAYTLiw4cOFAxVDzLix48eNbWAjkAOy5cuYM18W8CEtCAGaQ4se7TgCADs="></a></div></div> <div class="centerHack"><div style="margin-bottom: 1em;"><a href="http://sourceforge.net/donate/index.php?group_id=204582"><img alt="Support This Project" width="88" height="32" class="noBorder screenOnly" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD//gAXQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q/9sAQwABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/9sAQwEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/8AAEQgAIABYAwEiAAIRAQMRAf/EABwAAAICAwEBAAAAAAAAAAAAAAYIBwkAAgoFBP/EACsQAAEFAQEAAQIGAgIDAAAAAAYCAwQFBwEIEgkRABMUFRYhFyIYIyYxOP/EABgBAAMBAQAAAAAAAAAAAAAAAAMEBgUB/8QALBEAAwACAQQBAwALAAAAAAAAAQIDBBESAAUTIQYUIjEVIzIzQUNRYWJxkf/aAAwDAQACEQMRAD8Au28N/SW+l36X+ln4Xf2Xwv5nvSPRfE/l4kONBGsrG871m/Jr/Ewe2ISufqub14xpEgnuLZ+Ra3N84Srs7udIkPXMqaqRNdlUj/Ua+kwFfTmtB0tost8/a15UOiOKHjRuY+YvN7uiY+a28lyOM55qt9By2upyykJXG26QG039LW2M66YjjxrGdvrOARkNz3m/1mZYR9Nb6PoblkYev9L0Ty55ObfDCIF1gpZu8rocLygcNbVgoziG9SZRDHTPRcpUX6poj8+hAM+sS8upgDWC+nGc0Klee9N6x6QwWy827vsNHu+Q+iqtWaX2z3HnzZ6MjHNN0Dzdgb2UC1S4JefcGHsfjP8AqnTc+0/zmd6OBFYnr+FmMldvp+eGWVVFZqsn3D5n2PtveZdkyshly3fGlR1EzDGa8pma5NXqolRyToHQRQWooHEmJ7r8++Pdn77D47l3qM+rY0bOqxGNh0zERsVcijVTg9FfynlxQRUN7czTI57uBmLd79v+PPmDnef33i/MXnpHeJ5zveq6lecpVxP9fZPep/7Fd+DfzXxSUyJYeeAirGFFczzn4+5Hj1FISW45GxvyDP0YXEiZ2taGTc0yiAOSdNCgMm7ei6xo5KxKnEyFs2z9dLcTuaCE/v6rAmh9JgcPJlrbaXfCQ/eLQhCmm/laUkSY51hCVtJV2KuV1SFocdfWhlrv5qWVOOPtkC+qxHOpOUliQw31jQMhMcQLB0WPc9w8VWGWeKnYKQy7Gp9tCUWd6G1uiIc7C7bIgzENQzdADjue6WNUdXblnfNuezDWjyK2RYtBEpzsy1Xx1crNdD7WVlVS37SO+0C7DBi0+qrMtkyWTYk0uXpQMpnRwJleUyjrWSbGxqhfx7Vw4ZmmOoyUGYsjvUueevL7feK6nvF+Y/PX9dT3nFdV3mc9S2jny535u9QnvO/fne/ZXObpDMXT3/548w/2lSepX5e8+85zvec/63UKzX5pd/2SpDH2RI471tKko/35xoMo9O4oAY8e5wD7t6+y5VBm+sX6dSp85zfJdotSXT9/+mVSVIZhwyO+w5nCq2mjWCaZdHD7uoBUuqz4gLbFqhJ6yhuY0ohie2QusC88J39P9GR3qj0WekBL58DXBl6v9YC4P5/8JB1hc+6K9e41SRSk9Yk2f6iQlsi9E/T8dBFqO+V8uRqs0NIHz9QdwuHK/RPxDrJWc3DMzKaBiJY1FAEwCdhCp91nGWqFI9zyTQrPttios018ouXJIZp/bPDdSeKhgeO9svkSc/1vSeqD8Y6nrffPfmJziuJR1pvzH58+PX1c5xTKEs5yp1C1/djnOcU24t1fGo6nFcea/BBKyzMmBqmM3/OPl1I4QkxQK1FpzzZ5vU49fhVWD3hVD/bkgarSN2rqtIDrHtlZw41ZLRas9gzpKYF0zDmLL/cNIDWGO299/wAhL+IBTfJ7ZBgzcYYf87ZTJwHRsQLNP3nAlz9SRX2mz7pW5DpKCSkcx3G0qsfU2st22v30ceIbrWohIvThvonn4JynVtj9P6SeB+u6KezZemHFzoQBdiBzmuRidH2UXEekTSmvL86Is/0JQ0PfwKTS11TsBleQDGjmzryoIypkZj1mv0YnPyKtWdqMeJlZthQiHYdZAleaHkODspJB5ZedW+PM9uWKCgWz1Lu3iaNiWWaTRpMLiU3oC8WLFUcgll9a6wQJoKiffXPmXytBqqvuPfr5DXnfy7LVFRvOb2mw5O5yNDB3JczpbnVHckSOtxFdqWYX7Xc8prqTGqpgjIAsXjs1r/cH8lP/ALtAdsGWa3z15knyIDKLe3pVQruvgAk2wGrNMymmu8qCBqqu+1MqpJE16h4hG7a1mHSfduiEQyR9z/bvZIpqhUKeHaq8PZmg2QVPhz/MHnbc8r1gXhGgxr5SUkYPo+tHottlW5Y1o+gpJyA7vTQbqiSobvjAgsfaedd2qo0cRrNbyMDExfdxUYHxDJqeaRwKzRvXXpPcM/oRtvKfWPmU0yepHss2cPo7UiyvfRAgctRwpyR2vL8PNDGMSiXKzgitTDLNs/amwTxhJipDe1LUZyD+CBoetbXTN7msi1O3mjFQwM2dCpXDg7IymdnUvlNVUbxPoKV1oA9Ih6GEciZwTapVdhXnilsI+T6DKgWtB52xAfuK6cwL3S4djT29KCw7ekmsOtNciWVVYsSY7zCrKqlJeTGlcz8bexNWRp4d6QMUT9FsmCcBPlwp+qmRIbnEmDGBX6aEuzsjAw0Qnq63jEFpI2I32lapfAouimCbrW9ZsB13QyPPxpTZmkjOvB2G2TZPElVJB3+CP4j+vWxNmeU3ZDNmUM0yeTIxVSVZgFBIOwSFUf4jrqp87+eqn0z9NL6WMF69oAy5y/z/AOQjSGbyM1EzY8rqGmxUJs5lLmpNfdbl5iSySepDSuMWVzV3VyJgRXUeghWkAtuTCNsmelef7bwvgU703vhF5yZLMeZKkZzk+e5IBXYsSaGX5PnIQBkmd2EnP8hcz/XCX0ULU2o3xBXhZqQ0tGLg4QAFAiHRtHrjcH89fWe8JeWvBnkgKL9nqSbRwHy1gIjfZsFdVekcIsoMrEKS4GrFUdxqBR2tPZxZUeci6sKxiPIiOxX3+OcW12hX2x9Vif7mM6m3LyweCcxFHX5YDlzJDEmqgzZbbzP8qMpbLvYtuWdiPqRCjc69XUSH50ZhU7rqJLU5n/Eex9w7vDveXhu3ccUY7o4tkSTnFce0C8pb08nQHaoHqKUnkeZGKiS7h8E+Md377h/JszAN+6Y307zuuVkLKrY5x3xXtGdUSngpIUAXx+YVtK5rB1mjCsiuEDvhPHiLOBIwMNIpSM0BtPPu6rUjiM2SC0PnCOxHKsFlZzbTyUFq3zmxoBI+zfR/2dqYWZ+U6voMIj1QZ84ZMrfSNSP9O9WnqPi31C1I6phbXeNOsdT1DKk9QlClLj8QhDDzq1qbR+pShtebr1fJKBcbBC30VdlgCGWTlyHBJIdSrofFrNVLXjcVdRHsJb77cGlo6xiELU7j66cRbsCVsZgVKSwjVZC3+bc459uJOBrnOJRznOWkf7c7z5fLnE9cVzieq71aeJ+CUdW5ziP7+/418GWVNMhsugq9MvJaQQ0YLB8h2jvySkVImw9LNVAICgDrf7ZDPlLIPcKyraublvLxWrZVxnyqPjhmtj4vFliyjxziJSXjObOqh2ss8wB1VtO0VWf2wodHrT2e72YVgNmVjErNCNyTKfPura2LBInZTA7RW4VqakwLSiaHGgYqlcYuZH6CnlTv0yfxN2sZhk+R5Ro2jlmW7yMaTEcwwabwEs1YUpdF83GevxPby48Xe583AYl7o85VH5Qzrah0GjguB3d7l27DcWNbSa9FHoBbT9Q+khsUmzrIX1AdpbGzE9BBZ8tt0fsVSRHVc+Kcr0Gl7Hu4VpCbSRgBqTD65yIn7jWIs1WNRJg2sWHNjiELUchrksphk4gxyO2603xFlG538p7vVOtcWtTnUNuL4jvUuckc4lKOfbvW+9e7XHyK2LrktGXCKhFSjMeNPJQjX2KXXihJ3sAKfR11zJw8m2RzTJMZcIDigdqHjflYL/LDUmVA57RtBagoSOuguJ5tCR3csEGO0mogtOQe3vP+BZ7pR9OADkM9r5gcHpBT33qbzKKmGNQglrJhmEHBBHNHZr3qcCnUvpDIohYbTKl6HJ1X4qfyfjd3hGNabK04tG6M6Y8x2RN6MeC9yKsJoJm7mOVCWg0JOQyPLYF5gzVfnqRo93WHWhSPfh6mYcYnaZ1f55muhGtqNYvRlnfpUbyG7nE+X6KBiBVPrnKtBSmhAyQiHOdl18+ESZ1dGVIR2eWaMPz6qBZh2qZ3MG9ICrVhNiKFVRLcmuzgVvRcZbf/AFnCQP7L+Ckdd5ZR0fNCm+tuN94lf2+LyVOJV1xL/wCX1XF9S8hKo7gDh5rceOY01R9qeLM1AxBJfX3KE9BdbLbH40B0D9HZ7Mu+4vJE/dmatRnBcOBVnbmApI/Bb2zBOM1mo6CqfLB6gzj1QyReLvVmY6gz5RvD8SzDY9CArk+BKQE9KeU6u33ODWPedwvUoge5XaEQ/wAgt5WR54Gws8x3fwGk2k3s9AO7PzBWJ/Ju96rvVdQrqlKc5zq+K4txx13nO/fraFISlfFMPKS65IQ6txT63v1KnEwb0TF2EtoZIg5KGJKpbPxnRW1tSFc6hx5pxLilsPOI71TCo3WWoS3Oo/Ilx20sq97/ADbnX9f+dDP9c7z7JsYjaf7Wtzvfy0L43znycV1KUpTxvneoT92/y0NN48KRNWerWNWmV3zPAogQ+mGwGBGvet+/7dO4eLbHaxpdri1FcMxbYCwWIBDHa7Yhyp2AfXrXU1bAQdfyPUGPl37O56aN/HiU9+/5g3ZI4pS+r+X/ALVz785zvPt3vf77znO5+FuN9VCyIKMKGnLKSztbkWv6quroU5mRMnTrGqlwocSLHbUp19+TKfZZbaaQtfVL+/x+KVd5n4fljXuCZSdwG2So/HILre9fnR/50WuTjQKpa8ZMQWC0qiMVOgDpmB0T6/31/9k="></a></div></div> </div> </div> </div></div> <div class="box important" style="margin-top: 1em"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>You are always required to acknowledge the use of <span class="rkl">RegexKit<i>Lite</i></span> in your product as specified in the terms of the <a href="#LicenseInformation" class="hardNobr section-link">BSD License</a>.</p> </div></div></div></div> <h3 id="Introduction_Download">Download</h3> <p>You can download <span class="rkl">RegexKit<i>Lite</i></span> distribution that corresponds to this version of the documentation <span class="hardNobr">here&mdash;</span> <a href="http://downloads.sourceforge.net/regexkit/RegexKitLite-4.0.tar.bz2" class="printURL file">RegexKitLite-4.0.tar.bz2</a> (<span>139.1K</span>). To be automatically notified when a new version of <span class="rkl">RegexKit<i>Lite</i></span> is available, add the <a href="#NSString_RegexKitLiteAdditions__Xcode3IntegratedDocumentation"><span class="rkl">RegexKit<i>Lite</i></span> documentation feed</a> to Xcode.</p> <h3 id="Introduction_PDFDocumentation">PDF Documentation</h3> <p>This document is available in PDF format: <a href="http://downloads.sourceforge.net/regexkit/RegexKitLite-4.0.pdf" class="printURL file">RegexKitLite-4.0.pdf</a> (<span>1.1M</span>).</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>If you wish to print this document, it is recommend that you use the PDF version.</p> </div></div></div></div> <h3>Reporting Bugs</h3> <p>You can file bug reports, or review submitted bugs, at the following URL: <a href="http://sourceforge.net/tracker/?group_id=204582&amp;atid=990188"><span class="code">http://sourceforge.net/tracker/?group_id=204582&amp;atid=990188</span></a></p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>Anonymous bug reports are no longer accepted due to spam. A SourceForge.net account is required to file a bug report.</p> </div></div></div></div> <h3>Contacting The Author</h3> <p>The author can be contacted at <a href="mailto:regexkitlite@gmail.com"><span class="code">regexkitlite@gmail.com</span></a>.</p> </div> <div class="printPageBreakAfter"> <h2 id="RegexKitLiteOverview"><span class="hardNobr">RegexKit<i class="rk">Lite</i> Overview</span></h2> <p>While <span class="rkl">RegexKit<i>Lite</i></span> is not a descendant of the <span class="file">RegexKit.framework</span> source code, it does provide a small subset of <a href="http://regexkit.sourceforge.net/" class="section-link">RegexKits</a> <span class="code">NSString</span> methods for performing various regular expression tasks. These include determining the range that a regular expression matches within a string, easily creating a new string from the results of a match, splitting a string in to a <span class="code">NSArray</span> with a regular expression, and performing search and replace operations with regular expressions using common <span class="regex">$</span><span class="argument">n</span> substitution syntax.</p> <p><span class="rkl">RegexKit<i>Lite</i></span> uses the regular expression provided by the ICU library that ships with <span class="hardNobr">Mac OS X</span>. The two files, <span class="file">RegexKitLite.h</span> and <span class="file">RegexKitLite.m</span>, and linking against the <span class="file">/usr/lib/libicucore.dylib</span> ICU shared library is all that is required. Adding <span class="rkl">RegexKit<i>Lite</i></span> to your project only adds a few kilobytes of overhead to your applications size and typically only requires a few kilobytes of memory at run-time. Since a regular expression must first be compiled by the ICU library before it can be used, <span class="rkl">RegexKit<i>Lite</i></span> keeps a small <span class="hardNobr">4-way</span> set associative cache with a least recently used replacement policy of the compiled regular expressions.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://regexkit.sourceforge.net/" class="section-link">RegexKit Framework</a></li> <li><a href="http://site.icu-project.org/" class="section-link">International Components for Unicode</a></li> <li><a href="http://www.unicode.org/" class="section-link">Unicode Home Page</a></li> </ul> </div> <h3>Official Support from Apple for ICU Regular Expressions</h3> <h4>Mac OS X</h4> <p>As of <span class="hardNobr">Mac OS X 10.6</span>, the author is not aware of any official support from Apple for linking to the <span class="file">libicucore.dylib</span> library. On the other hand, the author is unaware of any official prohibition against it, either. Linking to the ICU library and making use of the ICU regular expression API is slightly different than making use of private, undocumented API's. There are a number of very good reasons why you shouldn't use private, undocumented API's, such as:</p> <ul class="square highlights"> <li>The undocumented, private API is not yet mature enough for Apple to commit to supporting it. Once an API is made "public", developers expect future versions to at least be compatible with previously published versions.</li> <li>The undocumented, private API may expose implementation specific details that can change between versions. Public API's are the proper "abstraction layer boundary" that allows the provider of the API to hide implementation specific details.</li> </ul> <p>The ICU library, on the other hand, contains a "published, public API" in which the ICU developers have committed to supporting in later releases, and <span class="rkl">RegexKit<i>Lite</i></span> uses only these public APIs. One could argue that Apple is not obligated to continue to include the ICU library in later versions of <span class="hardNobr">Mac OS X</span>, but this seems unlikely for a number of reasons which will not be discussed here. With the introduction of <span class="hardNobr">iPhone OS 3.2</span>, Apple now officially supports iPhone applications linking to the ICU library for the purpose of using its regular expression functionality. This is encouraging news for <span class="hardNobr">Mac OS X</span> developers if one assumes that Apple will try to keep some kind of parity between the <span class="hardNobr">iPhone OS</span> and <span class="hardNobr">Mac OS X</span> API's.</p> <h4>iPhone OS < 3.2</h4> <p>Prior to <span class="hardNobr">iPhone OS 3.2</span>, there was never any official support from Apple for linking to the <span class="file">libicucore.dylib</span> library. It was unclear if linking to the library would violate the <span class="hardNobr">iPhone OS SDK</span> Agreement prohibition against using undocumented API's, but a large number of iPhone applications choose to use <span class="rkl">RegexKit<i>Lite</i></span>, and the author is not aware of a single rejection because of it.</p> <h4>iPhone OS &ge; 3.2</h4> <p>Starting with <span class="hardNobr">iPhone OS 3.2</span>, Apple now officially allows <span class="hardNobr">iPhone OS</span> applications to <a href="http://developer.apple.com/iphone/library/releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS3_2.html#//apple_ref/doc/uid/TP40009337-SW25">link with the ICU library</a>. The ICU library contains a lot of functionality for dealing with internationalization and localization, but <a href="http://developer.apple.com/iphone/library/documentation/General/Conceptual/iPadProgrammingGuide/Text/Text.html#//apple_ref/doc/uid/TP40009370-CH8-SW31">Apple only officially permits the use of the ICU Regular Expression functionality</a>.</p> <p>Apple also provides a way to use ICU based regular expressions from <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html" class="section-link">Foundation</a> by adding a new option to <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/tdef/NSStringCompareOptions" class="code">NSStringCompareOptions</a>&ndash; <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSRegularExpressionSearch" class="code">NSRegularExpressionSearch</a>. This new option can be used with the <span class="code">NSString</span> <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/rangeOfString:options:" class="code">rangeOfString:options:</a> method, and the following example of its usage is given:</p> <div class="box sourcecode">// finds phone number in format nnn-nnn-nnnn NSRange r; NSString *regEx = @&quot;{3}-[0-9]{3}-[0-9]{4}&quot;; r = [textView.text rangeOfString:regEx options:NSRegularExpressionSearch]; if (r.location != NSNotFound) { NSLog(@&quot;Phone number is %@&quot;, [textView.text substringWithRange:r]); } else { NSLog(@&quot;Not found.&quot;); }</div> <p>At this time, <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/rangeOfString:options:" class="code">rangeOfString:options:</a> is the only regular expression functionality Apple has added to <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html" class="section-link">Foundation</a> and capture groups in a regular expression are not supported. Apple also gives the following note:</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>As noted in <a href="http://developer.apple.com/iphone/library/documentation/General/Conceptual/iPadProgrammingGuide/Text/Text.html#//apple_ref/doc/uid/TP40009370-CH8-SW31">"ICU Regular-Expression Support,"</a> the ICU libraries related to regular expressions are included in <span class="hardNobr">iPhone OS 3.2</span>. However, you should only use the ICU facilities if the <span class="code">NSString</span> alternative is not sufficient for your needs.</p> </div></div></div></div> <p><span class="rkl">RegexKit<i>Lite</i></span> provides a much richer API, such as the automatic extraction of a match as a <span class="code">NSString</span>. Using <span class="rkl">RegexKit<i>Lite</i></span>, the example can be rewritten as:</p> <div class="box sourcecode">// finds phone number in format nnn-nnn-nnnn NSString *regEx = @&quot;{3}-[0-9]{3}-[0-9]{4}&quot;; NSString *match = [textView.text stringByMatching:regEx]; if ([match isEqual:@&quot;&quot;] == NO) { NSLog(@&quot;Phone number is %@&quot;, match); } else { NSLog(@&quot;Not found.&quot;); }</div> <p>What's more, <span class="rkl">RegexKit<i>Lite</i></span> provides easy access to all the matches of a regular expression in a <span class="code">NSString</span>:</p> <div class="box sourcecode">// finds phone number in format nnn-nnn-nnnn NSString *regEx = @&quot;{3}-[0-9]{3}-[0-9]{4}&quot;; for(NSString *match in [textView.text componentsMatchedByRegex:regEx]) { NSLog(@&quot;Phone number is %@&quot;, match); }</div> <p>To do the same thing using just <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSRegularExpressionSearch" class="code">NSRegularExpressionSearch</a> would require significantly more code and effort on your part. <span class="rkl">RegexKit<i>Lite</i></span> also provides powerful search and replace functionality:</p> <div class="box sourcecode">// finds phone number in format nnn-nnn-nnnn NSString *regEx = @&quot;({3})-([0-9]{3}-[0-9]{4})&quot;; // and transforms the phone number in to the format of (nnn) nnn-nnnn NSString *replaced = [textView.text stringByReplacingOccurrencesOfRegex:regEx withString:@&quot;($1) $2&quot;];</div> <p><span class="rkl">RegexKit<i>Lite</i></span> also has a number of performance enhancing features built in such as caching compiled regular expressions. Although the author does not have any benchmarks comparing <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSRegularExpressionSearch" class="code">NSRegularExpressionSearch</a> to <span class="rkl">RegexKit<i>Lite</i></span>, it is likely that <span class="rkl">RegexKit<i>Lite</i></span> outperforms <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSRegularExpressionSearch" class="code">NSRegularExpressionSearch</a>.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/iphone/library/releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS3_2.html#//apple_ref/doc/uid/TP40009337-SW25" class="section-link">What's New in iPhone OS - ICU Regular-Expression Support</a></li> <li><a href="http://developer.apple.com/iphone/library/releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS3_2.html#//apple_ref/doc/uid/TP40009337-SW17" class="section-link">What's New in iPhone OS - Foundation Framework Changes</a></li> <li><a href="http://developer.apple.com/iphone/library/documentation/General/Conceptual/iPadProgrammingGuide/Text/Text.html#//apple_ref/doc/uid/TP40009370-CH8-SW31" class="section-link">iPad Programming Guide - ICU Regular-Expression Support</a></li> <li><a href="http://developer.apple.com/iphone/library/documentation/General/Conceptual/iPadProgrammingGuide/Text/Text.html#//apple_ref/doc/uid/TP40009370-CH8-SW33" class="section-link">iPad Programming Guide - Foundation-Level Regular Expressions</a></li> <li><a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/c/econst/NSRegularExpressionSearch" class="code">NSRegularExpressionSearch</a></li> <li><a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/rangeOfString:options:" class="code">- rangeOfString:options:</a></li> </ul> </div> <h4>The iPhone 4.0 SDK Agreement</h4> <p>While <span class="hardNobr">iPhone OS 3.2</span> included official, Apple sanctioned use of linking of the ICU library for the purposes of using the ICU regular expression engine, the <span class="hardNobr">iPhone OS 4.0 SDK</span> included the following change to the <span class="hardNobr">iPhone OS SDK</span> Agreement:</p> <div class="table"><div class="row"><div class="cell" style="padding-left: 2.5ex; padding-right: 1.5ex;">3.3.1</div><div class="cell"><p style="max-width: 6.125in; text-align: justify;">Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs. Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs (e.g., Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited).</p></div></div></div> <p>This raises a number of obvious questions:</p> <ul class="square highlights"> <li>Does 3.3.1 apply to <span class="rkl">RegexKit<i>Lite</i></span>?</li> <li>Will the use of <span class="rkl">RegexKit<i>Lite</i></span> in an <span class="hardNobr">iPhone OS</span> application be grounds for rejection under 3.3.1?</li> </ul> <p>There is considerable speculation as to what is covered by this change, but at the time of this writing, there is no empirical evidence or official guidelines from Apple to make any kind of an informed decision as to whether or not the use of <span class="rkl">RegexKit<i>Lite</i></span> would violate 3.3.1. It is the authors opinion that <span class="rkl">RegexKit<i>Lite</i></span> could be considered as a <i>compatibility layer</i> between <span class="code">NSString</span> and the now <i>Documented APIs</i> for regular expressions in the ICU library.</p> <p>It is widely speculated that the motivation for the change to 3.3.1 was to prevent the development of Flash applications for the iPhone. The author believes that most reasonable people would consider the application of <i>compatibility layer</i> in this context to mean something entirely different than what it means when applied to <span class="rkl">RegexKit<i>Lite</i></span>.</p> <p>At this time, the author is not aware of a single iPhone application that has been rejected due to the use of <span class="rkl">RegexKit<i>Lite</i></span>. If your application is rejected due to the use of <span class="rkl">RegexKit<i>Lite</i></span>, please let the author know by emailing <a href="mailto:regexkitlite@gmail.com"><span class="consoleText">regexkitlite@gmail.com</span></a>. As always, <span style="font-family: courier, monospace">CAVEAT EMPTOR</span>.</p> <h3>The Difference Between RegexKit.framework and <span class="rkl">RegexKit<i>Lite</i></span></h3> <p>RegexKit.framework and <span class="rkl">RegexKit<i>Lite</i></span> are two different projects. In retrospect, <span class="rkl">RegexKit<i>Lite</i></span> should have been given a more distinctive name. Below is a table summarizing some of the key differences between the two:</p> <table class="standard"> <tr><th>&nbsp;</th><th>RegexKit.framework</th><th><span class="rkl">RegexKit<i>Lite</i></span></th></tr> <tr><td><b>Regex Library</b></td><td>PCRE</td><td>ICU</td></tr> <tr><td><b>Library Included</b></td><td>Yes, built into framework object file.</td><td>No, provided by <span class="hardNobr">Mac OS X.</span></td></tr> <tr><td><b>Library Linked As</b></td><td>Statically linked into framework.</td><td>Dynamically linked to <span class="file">/usr/lib/libicucore.dylib.</span></td></tr> <tr><td><b>Compiled Size</b></td><td>Approximately <span class="hardNobr">371KB<sup>&dagger;</sup></span> per architecture.</td><td>Very small, approximately <span class="hardNobr">16KB&mdash;20KB<sup>&Dagger;</sup></span> per architecture.</td></tr> <tr><td><b>Style</b></td><td>External, linked to framework.</td><td>Compiled directly in to final executable.</td></tr> <tr><td><b>Feature Set</b></td><td>Large, with additions to many classes.</td><td>Minimal, <span class="code">NSString</span> only.</td></tr> </table> <div class="table" style="margin: 1em 0px"> <div class="row"><div class="cell"><sup>&dagger;</sup></div><div class="cell"><span style="margin:0px 1ex">-</span></div><div class="cell"><span class="hardNobr">Version 0.6.0.</span> About half of the <span class="hardNobr">371KB</span> is the PCRE library.<br> The default distribution framework shared library file is <span class="hardNobr">1.4MB</span> in size and includes the <span class="quotedText">ppc</span>, <span class="quotedText">ppc64</span>, <span class="quotedText">i386</span>, and <span class="quotedText">x86_64</span> architectures.<br> If <span class="hardNobr">64-bit</span> support is removed, the framework shared library file size drops to <span class="hardNobr">664KB</span>.</div></div> <div class="row"><div class="cell"><sup>&Dagger;</sup></div><div class="cell"><span style="margin:0px 1ex">-</span></div><div class="cell">Since the ICU library is part of <span class="hardNobr">Mac OS X,</span> it does not add to the final size.</div></div> </div> <h3>Compiled Regular Expression Cache</h3> <p>The <span class="code">NSString</span> that contains the regular expression must be compiled in to an ICU <a href="http://www.icu-project.org/apiref/icu4c/uregex_8h.html#566882c83d9e4dcf7fb5d8f859625500" class="code">URegularExpression</a>. This can be an expensive, time consuming step, and the compiled regular expression can be reused again in another search, even if the strings to be searched are different. Therefore <span class="rkl">RegexKit<i>Lite</i></span> keeps a small cache of recently compiled regular expressions.</p> <p>The cache is organized as a 4-way set associative cache, and the size of the cache can be tuned with the <span class="hardNobr">pre-processor</span> define <span class="cpp_flag">RKL_CACHE_SIZE</span>. The default cache size, which should always be a prime number, is set to <span class="code">13</span>. Since the cache is 4-way set associative, the total number of compiled regular expressions that can be cached is <span class="cpp_flag">RKL_CACHE_SIZE</span> times four, for a total of <span class="code">13 * 4</span>, or <span class="code">52</span>. The <span class="code">NSString</span> <span class="argument">regexString</span> is mapped to a cache set using modular arithmetic: <span class="hardNobr">Cache set &equiv; <span class="code">[regexString hash]</span> mod <span class="cpp_flag">RKL_CACHE_SIZE</span>,</span> <span class="hardNobr">i.e.</span> <span class="hardNobr"><span class="code">cacheSet = [regexString hash] % 13;</span>.</span> Since <span class="rkl">RegexKit<i>Lite</i></span> uses <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a>, this is actually coded <span class="hardNobr"> as <span class="code">cacheSet = CFHash(regexString) % <span class="cpp_flag">RKL_CACHE_SIZE</span>;</span>.</span></p> <p>Each of the four &quot;ways&quot; of a cache set are checked to see if it contains a <span class="code">NSString</span> that was used to create the compiled regular expression that is identical to the <span class="code">NSString</span> for the regular expression that is being checked. If there is an exact match, then the matching &quot;way&quot; is updated as the most recently used, and the compiled regular expression is used as-is. Otherwise, the least recently used, or LRU, &quot;way&quot; in the cache set is cleared and replaced with the compiled regular expression for the regular expression that wasn't in the cache.</p> <p>In addition to the compiled regular expression cache, <span class="rkl">RegexKit<i>Lite</i></span> keeps a small lookaside cache that maps a regular expressions <span class="code">NSString</span> pointer and <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> directly to a cached compiled regular expression. When a regular expressions <span class="code">NSString</span> pointer and <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> is in the lookaside cache, <span class="rkl">RegexKit<i>Lite</i></span> can bypass calling <span class="code">CFHash(regexString)</span> and checking each of the four &quot;ways&quot; in a cache set since the lookaside cache has provided the exact cached compiled regular expression. The lookaside cache is quite small at just 64 bytes and it was added because <span class="file hardNobr">Shark.app</span> profiling during performance tuning showed that <span class="code hardNobr">CFHash()</span>, while quite fast, was the primary bottleneck when retrieving already compiled and cached regular expressions, typically accounting for &cong;40% of the look up time.</p> <h4>Regular Expressions in Mutable Strings</h4> <p>When a regular expression is compiled, an immutable copy of the string is kept. For immutable <span class="code">NSString</span> objects, the copy is usually the same object with its reference count increased by one. Only <span class="code">NSMutableString</span> objects will cause a new, immutable <span class="code">NSString</span> to be created.</p> <p>If the regular expression being used is stored in a <span class="code">NSMutableString</span>, the cached regular expression will continue to be used as long as the <span class="code">NSMutableString</span> remains unchanged. Once mutated, the changed <span class="code">NSMutableString</span> will no longer be a match for the cached compiled regular expression that was being used by it previously. Even if the newly mutated strings <span class="code">hash</span> is congruent to the previous unmutated strings <span class="code">hash</span> modulo <span class="cpp_flag">RKL_CACHE_SIZE</span>, that is to say they share the same cache set <span class="hardNobr">(i.e.,</span> <span class="code"><span class="hardNobr">([mutatedString hash] % <span class="cpp_flag">RKL_CACHE_SIZE</span>)</span> == <span class="hardNobr">([unmutatedString hash] % <span class="cpp_flag">RKL_CACHE_SIZE</span>)</span>)</span>, the immutable copy of the regular expression string used to create the compiled regular expression is used to ensure true equality. The newly mutated string will have to go through the whole regular expression compile and cache creation process.</p> <p>This means that <span class="code">NSMutableString</span> objects can be safely used as regular expressions, and any mutations to those objects will immediately be detected and reflected in the regular expression used for matching.</p> <h4>Searching Mutable Strings</h4> <p>Unfortunately, the ICU regular expression API requires that the compiled regular expression be <span class="hardNobr">"set"</span> to the string to be searched. To search a different string, the compiled regular expression must be <span class="hardNobr">"set"</span> to the new string. Therefore, <span class="rkl">RegexKit<i>Lite</i></span> tracks the last <span class="code">NSString</span> that each compiled regular expression was set to, recording the pointer to the <span class="code">NSString</span> object, its hash, and its length. If any of these parameters are different from the last parameters used for a compiled regular expression, the compiled regular expression is <span class="hardNobr">"set"</span> to the new string. Since mutating a string will likely change its <span class="code">hash</span> value, it&#39;s generally safe to search <span class="code">NSMutableString</span> objects, and in most cases the mutation will reset the compiled regular expression to the updated contents of the <span class="code">NSMutableString</span>.</p> <div class="box caution"><div class="table"><div class="row"><div class="label cell">Caution:</div><div class="message cell"><p>Care must be taken when mutable strings are searched and there exists the possibility that the string has mutated between searches. See <a href="#NSString_RegexKitLiteAdditions__CachedInformationandMutableStrings" class="section-link">NSString <span class="rkl">RegexKit<i>Lite</i></span> Additions Reference - Cached Information and Mutable Strings</a> for more information.</p></div></div></div></div> <h4>Last Match Information</h4> <p>When performing a match, the arguments used to perform the match are kept. If those same arguments are used again, the actual matching operation is skipped because the compiled regular expression already contains the results for the given arguments. This is mostly useful when a regular expression contains multiple capture groups, and the results for different capture groups for the same match are needed. This means that there is only a small penalty for iterating over all the capture groups in a regular expression for a match, and essentially becomes the direct ICU regular expression API equivalent of <a href="http://www.icu-project.org/apiref/icu4c/uregex_8h.html#5a2eccd52a16efe1ba99c53d56614a4f" class="code hardNobr">uregex_start()</a> and <a href="http://www.icu-project.org/apiref/icu4c/uregex_8h.html#3f5e9eba75d943ff1aba3d3dc779a67f" class="code hardNobr">uregex_end()</a>.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://www.icu-project.org/apiref/icu4c/uregex_8h.html" class="section-link printURL">ICU4C C API - Regular Expressions</a></li> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> </ul> </div> <h3><span class="code hardNobr">UTF-16</span> Conversion Cache</h3> <p><span class="rkl">RegexKit<i>Lite</i></span> is ideal when the string being matched is a <span class="hardNobr">non-<span class="code">ASCII</span>,</span> Unicode string. This is because the regular expression engine used, ICU, can only operate on <span class="code hardNobr">UTF-16</span> encoded strings. Since Cocoa keeps essentially all <span class="hardNobr">non-<span class="code">ASCII</span></span> strings encoded in <span class="code hardNobr">UTF-16</span> form internally, this means that <span class="rkl">RegexKit<i>Lite</i></span> can operate directly on the strings buffer without having to make a temporary copy and transcode the string in to ICU&#39;s required format.</p> <p>Like all object oriented programming, the internal representation of an objects information is private. However, the ICU regular expression engine requires that the text to be search be encoded as a <span class="code hardNobr">UTF-16</span> string. For pragmatic purposes, <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> has several public functions that can provide direct access to the buffer used to hold the contents of the string, but such direct access is only available if the private buffer is already encoded in the requested direct access format. As a rough rule of thumb, <span class="hardNobr">8-bit</span> simple strings, such as <span class="code">ASCII</span>, are kept in their <span class="hardNobr">8-bit</span> format. Non <span class="hardNobr">8-bit</span> simple strings are stored as <span class="code hardNobr">UTF-16</span> strings. Of course, this is an implementation private detail, so this behavior should never be relied upon. It is mentioned because of the tremendous impact on matching performance and efficiency it can have if a string must be converted to <span class="hardNobr code">UTF-16</span>.</p> <p>For strings in which direct access to the <span class="code hardNobr">UTF-16</span> string is available, <span class="rkl">RegexKit<i>Lite</i></span> uses that buffer. This is the ideal case as no extra work needs to be performed, such as converting the string in to a <span class="code hardNobr">UTF-16</span> string, and allocating memory to hold the temporary conversion. Of course, direct access is not always available, and occasionally the string to be searched will need to be converted in to a <span class="code hardNobr">UTF-16</span> string.</p> <p><span class="rkl">RegexKit<i>Lite</i></span> has two conversion cache types. Each conversion cache type contains four buffers each, and buffers are re-used on a least recently used basis. If the selected cache type does not contain the contents of the <span class="code">NSString</span> that is currently being searched in any of its buffers, the least recently used buffer is cleared and the current <span class="code">NSString</span> takes it place. The first conversion cache type is fixed in size and set by the <span class="hardNobr">C pre-processor</span> define <span class="cpp_flag">RKL_FIXED_LENGTH</span>, which defaults to <span class="code">2048</span>. Any string whose length is less than <span class="cpp_flag">RKL_FIXED_LENGTH</span> will use the fixed size conversion cache type. The second conversion cache type, for strings whose length is longer than <span class="cpp_flag">RKL_FIXED_LENGTH</span>, will use a dynamically sized conversion buffer. The memory allocation for the dynamically sized conversion buffer is resized for each conversion with <span class="code hardNobr">realloc()</span> to the size needed to hold the entire contents of the <span class="code hardNobr">UTF-16</span> converted string.</p> <p>This strategy was chosen for its relative simplicity. Keeping track of dynamically created resources is required to prevent memory leaks. As designed, there are only four pointers to dynamically allocated memory: the four pointers to hold the conversion contents of strings whose length is larger than <span class="cpp_flag">RKL_FIXED_LENGTH</span>. However, since <span class="code hardNobr">realloc()</span> is used to manage those memory allocations, it becomes very difficult to accidentally leak the buffers. Having the fixed sized buffers means that the memory allocation system isn&#39;t bothered with many small requests, most of which are transient in nature to begin with. The current strategy tries to strike the best balance between performance and simplicity.</p> <h4>Mutable Strings</h4> <p>When converted in to a <span class="code hardNobr">UTF-16</span> string, the <span class="code">hash</span> of the <span class="code">NSString</span> is recorded, along with the pointer to the <span class="code">NSString</span> object and the strings length. In order for the <span class="rkl">RegexKit<i>Lite</i></span> to use the cached conversion, all of these parameters must be equal to their values of the <span class="code">NSString</span> to be searched. If there is any difference, the cached conversion is discarded and the current <span class="code">NSString</span>, or <span class="code">NSMutableString</span> as the case may be, is reconverted in to a <span class="code hardNobr">UTF-16</span> string.</p> <div class="box caution"><div class="table"><div class="row"><div class="label cell">Caution:</div><div class="message cell"><p>Care must be taken when mutable strings are searched and there exists the possibility that the string has mutated between searches. See <a href="#NSString_RegexKitLiteAdditions__CachedInformationandMutableStrings" class="section-link">NSString <span class="rkl">RegexKit<i>Lite</i></span> Additions Reference - Cached Information and Mutable Strings</a> for more information.</p></div></div></div></div> <h3>Multithreading Safety</h3> <p><span class="rkl">RegexKit<i>Lite</i></span> is also multithreading safe. Access to the compiled regular expression cache and the conversion cache is protected by a single <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html" class="code">OSSpinLock</a> to ensure that only one thread has access at a time. The lock remains held while the regular expression match is performed since the compiled regular expression returned by the ICU library is not safe to use from multiple threads. Once the match has completed, the lock is released, and another thread is free to lock the cache and perform a match.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>While it is safe to use the same regular expression from any thread at any time, the usual multithreading caveats apply. For example, it is not safe to mutate a <span class="code">NSMutableString</span> in one thread while performing a match on the mutating string in another.</p> </div></div></div></div> <p>If Blocks functionality is enabled, and a <span class="rkl">RegexKit<i>Lite</i></span> method that takes a Block as one of its parameters is used, <span class="rkl">RegexKit<i>Lite</i></span> takes a slightly different approach in order to support the asynchronous, and possibly re-entrant, nature of Blocks.</p> <p>First, an autoreleased Block helper proxy object is created and is used to keep track of any Block local resources needed to perform a Block-based enumeration.</p> <p>Then the regular expression cache is checked exactly as before. Once a compiled regular expression is obtained, the ICU function <a href="http://icu-project.org/apiref/icu4c/uregex_8h.html#a3befb11b7c9b28c19af6114ed19b7339" class="code">uregex_clone</a> is used to create a Block local copy of the regular expression. After the Block local copy has been made, the global compiled regular expression cache lock is unlocked.</p> <p>If the string to be searched requires conversion to <span class="hardNobr code">UTF-16</span>, then a one time use Block local <span class="hardNobr code">UTF-16</span> conversion of the string is created.</p> <p>These changes mean that <span class="rkl">RegexKit<i>Lite</i></span> Block-based enumeration methods are just as multithreading safe and easy to use as non-Block-based enumeration methods, such as the ability to continue to use <span class="rkl">RegexKit<i>Lite</i></span> methods without any restrictions from within the Block used for enumeration.</p> <h3>64-bit Support</h3> <p><span class="rkl">RegexKit<i>Lite</i></span> is <span class="hardNobr">64-bit</span> clean. Internally, <span class="rkl">RegexKit<i>Lite</i></span> uses Cocoas standard <span class="code">NSInteger</span> and <span class="code">NSUInteger</span> types for representing integer values. The size of these types change between <span class="hardNobr">32-bit</span> and <span class="hardNobr">64-bit</span> automatically, depending on the target architecture. ICU, on the other hand, uses a signed <span class="hardNobr">32-bit</span> <span class="code">int</span> type for many of its arguments, such as string offset values. Because of this, the maximum length of a string that <span class="rkl">RegexKit<i>Lite</i></span> will accept is the maximum value that can be represented by a signed 32-bit integer, which is approximately 2 gigabytes. Strings that are longer this limit will raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSRangeException" class="code">NSRangeException</a>. This limitation may be significant to those who are switching to <span class="hardNobr">64-bit</span> because the size of the data they need to process exceeds what can be represented with <span class="hardNobr">32-bits.</span></p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>Several numeric constants throughout this document will have either <span class="code">L</span> or <span class="code">UL</span> appended to them&mdash; for example <span class="code">0UL</span>, or <span class="code">2L</span>. This is to ensure that they are treated as <span class="hardNobr">64-bit</span> <span class="code">long</span> or <span class="code">unsigned long</span> values, respectively, when targeting a <span class="hardNobr">64-bit</span> architecture.</p> </div></div></div></div> </div> <div class="printPageBreakAfter"> <h2 id="UsingRegexKitLite">Using <span class="rkl">RegexKit<i>Lite</i></span></h2> <p>The goal of <span class="rkl">RegexKit<i>Lite</i></span> is not to be a comprehensive <span class="hardNobr">Objective-C</span> regular expression framework, but to provide a set of easy to use primitives from which additional functionality can be created. To this end, <span class="rkl">RegexKit<i>Lite</i></span> provides the following two core primitives from which everything else is built:</p> <ul class="square highlights"> <li><span class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">captureCountWithOptions:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></span></li> <li><span class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="selector">rangeOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></span></li> </ul> <p>There is often a need to create a new string of the characters that were matched by a regular expression. <span class="rkl">RegexKit<i>Lite</i></span> provides the following method which conveniently combines sending the receiver <span class="code">substringWithRange:</span> with the range returned by <span class="code">rangeOfRegex:</span>.</p> <ul class="square highlights"> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByMatching:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> </ul> <p><span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 2.0</span> adds the ability to split strings by dividing them with a regular expression, and the ability to perform search and replace operations using common <span class="hardNobr"><span class="regex">$</span><span class="argument">n</span></span> substitution syntax. <a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" title="Replaces all occurrences of the regular expression regex with the contents of replacement string after performing capture group substitutions, returning the number of replacements made." class="code">replaceOccurrencesOfRegex:withString:</a> is used to modify the contents of <span class="code">NSMutableString</span> objects directly and <a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" title="Returns a string created from the characters of the receiver that are in the range of the first match of regex." class="code">stringByReplacingOccurrencesOfRegex:withString:</a> will create a new, immutable <span class="code">NSString</span> from the receiver.</p> <ul class="square highlights"> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSUInteger">NSUInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> </ul> <p><span class="rkl">RegexKit<i>Lite</i></span> 3.0 adds several new methods that return a <span class="code">NSArray</span> containing the aggregated results of a number of individual regex operations.</p> <ul class="square highlights"> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfCaptureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">captureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div></li> </ul> <p><span class="rkl">RegexKit<i>Lite</i></span> 4.0 adds several new methods that take advantage of the new blocks language extension.</p> <ul class="square highlights"> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)</span><span class="selector">enumerateStringsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span><span class="hardNobr">(void (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)</span><span class="selector">enumerateStringsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span><span class="hardNobr">(void (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)</span><span class="selector">enumerateStringsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span><span class="hardNobr">(void (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)</span><span class="selector">enumerateStringsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span><span class="hardNobr">(void (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)</span><span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)</span><span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSUInteger">NSUInteger</a>)</span><span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSUInteger">NSUInteger</a>)</span><span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> (^)</span><span class="hardNobr">(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,</span> <span class="hardNobr"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],</span> <span class="hardNobr">const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],</span> <span class="hardNobr">volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</span></div></li> </ul> <p>There are no additional classes that supply the regular expression matching functionality, everything is accomplished with the two methods above. These methods are added to the existing <span class="code">NSString</span> class via an <span class="hardNobr">Objective-C</span> category extension. See <a href="#RegexKitLiteNSStringAdditionsReference" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference</a> for a complete list of methods.</p> <p>The real workhorse is the <a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:" class="code hardNobr">rangeOfRegex:options:inRange:capture:error:</a> method. The receiver of the message is an ordinary <span class="code">NSString</span> class member that you wish to perform a regular expression match on. The parameters of the method are a <span class="code">NSString</span> containing the regular expression <span class="argument">regex</span>, any <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> match <span class="argument">options</span>, the <span class="code">NSRange</span> <span class="argument">range</span> of the receiver that is to be searched, the <span class="argument">capture</span> number from the regular expression <span class="argument">regex</span> that you would like the result for, and an optional <span class="argument">error</span> parameter that will contain a <span class="code">NSError</span> object if a problem occurs with the details of the error.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>The <span class="hardNobr">C language</span> assigns special meaning to <span class="hardNobr">the <span class="consoleText">\</span> character</span> when inside a <span class="hardNobr">quoted <span class="consoleText">"&nbsp;"</span> string</span> in your source code. <span class="hardNobr">The <span class="consoleText">\</span> character</span> is the escape character, and the character that follows has a different meaning than normal. The most common example of this <span class="hardNobr">is <span class="consoleText">\n</span>,</span> which translates in to the <span class="regex-def">new-line</span> character. Because of this, you are required to <span class="hardNobr">&#39;escape&#39;</span> any uses <span class="hardNobr">of <span class="consoleText">\</span> by</span> prepending it with <span class="hardNobr">another <span class="consoleText">\</span>.</span> In practical terms this means doubling <span class="hardNobr">any <span class="consoleText">\</span> in</span> a regular expression, which unfortunately is quite common, that are inside of <span class="hardNobr">quoted <span class="consoleText">"&nbsp;"</span> strings</span> in your source code. Failure to do so will result in numerous warnings from the compiler about unknown escape sequences. To match a single literal <span class="consoleText">\</span> with a regular expression requires no less than four backslashes: <span class="consoleText">&quot;\\\\&quot;</span>.</p> </div></div></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> <li><a href="#RegexKitLiteCookbook" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> Cookbook</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> <h3>Finding the Range of a Match</h3> <p>A simple example:</p> <div class="box sourcecode"><div>NSString *searchString = <span class="hardNobr">@&quot;This is neat.&quot;;</span> NSString *regexString = <span class="hardNobr">@&quot;(\\w+)\\s+(\\w+)\\s+(\\w+)&quot;;</span> NSRange matchedRange = <span class="hardNobr">NSMakeRange(NSNotFound, 0UL);</span> NSError *error = NULL; <span class="hardNobr">matchedRange = [searchString</span> <span class="hardNobr">rangeOfRegex:regexString</span> <span class="hardNobr">options:RKLNoOptions</span> <span class="hardNobr">inRange:searchRange</span> <span class="hardNobr">capture:2L</span> <span class="hardNobr">error:&amp;error];</span> NSLog(@&quot;matchedRange: %@&quot;, NSStringFromRange(matchedRange)); // <span class="comment">2008-03-18 03:51:16.530 test[51583:813] matchedRange: {5, 2}</span></div><div class="metainfo bottom noPrintBorder"><span class="entry continues below"><span class="item meta">Continues&hellip;</span></span></div><div class="floatRightPadder noSelect">&nbsp;</div></div> <p>In the previous example, the <span class="code">NSRange</span> that capture number <span class="code">2</span> matched is <span class="code hardNobr">{5, 2}</span>, which corresponds to the word <span class="quotedText">is</span> in <span class="code">searchString</span>. Once the <span class="code">NSRange</span> is known, you can create a new string containing just the matching text:</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;example</span></span></div><div><span class="hardNobr">NSString *matchedString = [searchString</span> <span class="hardNobr">substringWithRange:matchedRange];</span> NSLog(@&quot;matchedString: &#39;%@&#39;&quot;, matchedString); // <span class="comment">2008-03-18 03:51:16.532 test[51583:813] matchedString: &#39;is&#39;</span></div></div> <p><span class="rkl">RegexKit<i>Lite</i></span> can conveniently combine the two steps above with <span class="code">stringByMatching:</span>. This example also demonstrates the use of one of the simpler convenience methods, where some of the arguments are automatically filled in with default values:</p> <div class="box sourcecode"><div>NSString *searchString = <span class="hardNobr">@&quot;This is neat.&quot;;</span> NSString *regexString = <span class="hardNobr">@&quot;(\\w+)\\s+(\\w+)\\s+(\\w+)&quot;;</span> NSString *matchedString = [searchString <span class="hardNobr">stringByMatching:regexString</span> <span class="hardNobr">capture:2L];</span> NSLog(@&quot;matchedString: &#39;%@&#39;&quot;, matchedString); // <span class="comment">2008-03-18 03:53:42.949 test[51583:813] matchedString: &#39;is&#39;</span></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:" class="code">- rangeOfRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:" class="code">- stringByMatching:</a></li> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> </ul> </div> <h3>Search and Replace</h3> <p>You can perform search and replace operations on <span class="code">NSString</span> objects and use common <span class="hardNobr"><span class="regex">$</span><span class="argument">n</span></span> capture group substitution in the replacement string:</p> <div class="box sourcecode">NSString *searchString = <span class="hardNobr">@&quot;This is neat.&quot;;</span> NSString *regexString = <span class="hardNobr">@&quot;\\b(\\w+)\\b&quot;;</span> NSString *replaceWithString = <span class="hardNobr">@&quot;{$1}&quot;;</span> NSString *replacedString = <span class="hardNobr">NULL;</span> replacedString = <span class="hardNobr">[searchString</span> <span class="hardNobr">stringByReplacingOccurrencesOfRegex:regexString</span> <span class="hardNobr">withString:replaceWithString];</span> NSLog(@&quot;replaced string: &#39;%@&#39;&quot;, replacedString); // <span class="comment">2008-07-01 19:03:03.195 test[68775:813] replaced string: &#39;<span class="hardNobr">{This}</span> <span class="hardNobr">{is}</span> <span class="hardNobr">{neat}.&#39;</span></span></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Search and replace methods will raise a <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if the <span class="argument">replacementString</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression.</div></div></div></div> <p>In this example, the regular expression <span class="regex">\b(\w+)\b</span> has a single capture group, which is created with the use of <span class="regex">()</span> parenthesis. The text that was matched inside the parenthesis is available for use in the replacement text by using <span class="hardNobr"><span class="regex">$</span><span class="argument" title="Decimal Number">n</span></span>, where <span class="argument" title="Decimal Number">n</span> is the parenthesized capture group you would like to use. Additional capture groups are numbered sequentially in the order that they appear from left to right. Capture group <span class="consoleText" title="Zero">0</span> (zero) is also available and is equivalent to all the text that the regular expression matched.</p> <p>Mutable strings can be manipulated directly:</p> <div class="box sourcecode">NSMutableString *mutableString <span class="hardNobr">= [NSMutableString</span> <span class="hardNobr">stringWithString:@&quot;This is neat.&quot;];</span> NSString *regexString <span class="hardNobr">= @&quot;\\b(\\w+)\\b&quot;;</span> NSString *replaceWithString <span class="hardNobr">= @&quot;{$1}&quot;;</span> NSUInteger replacedCount <span class="hardNobr">= 0UL;</span> replacedCount = <span class="hardNobr">[mutableString</span> <span class="hardNobr">replaceOccurrencesOfRegex:regexString</span> <span class="hardNobr">withString:replaceWithString];</span> NSLog(@&quot;count: %lu string: &#39;%@&#39;&quot;, (u_long)replacedCount, mutableString); // <span class="comment">2008-07-01 21:25:43.433 test[69689:813] <span class="hardNobr">count: 3</span> string: &#39;<span class="hardNobr">{This}</span> <span class="hardNobr">{is}</span> <span class="hardNobr">{neat}.&#39;</span></span></div> <h4>Search and Replace using Blocks</h4> <span class="rkl">RegexKit<i>Lite</i></span> 4.0 adds support for performing the same search and replacement on strings, except now the contents of the replacement string are created by the Block that is passed as the argument. For each match that is found in the string, the Block argument is called and passed the details of the match which includes a C array of <span class="code">NSString</span> objects, one for each capture, along with a C array of <span class="code">NSRange</span> structures with the range information for the current match. The text that was matched will be replaced with the <span class="code">NSString</span> object that the Block is required to return. % This allows you complete control over the contents of the replaced text, such as doing complex transformations of the matched text, which is much more flexible and powerful than the simple, fixed replacement functionality provided by <a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">stringByReplacingOccurrencesOfRegex:withString:</a>. The example below is essentially the same as the previous search and replace examples, except this example uses the <span class="code">capitalizedString</span> method to capitalize the matched result, which is then used in the string that is returned as the replacement text. Note that the first letter in each word in <span class="code">replacedString</span> is now capitalized. <div class="box sourcecode">NSString *searchString = @&quot;This is neat.&quot;; NSString *regexString = @&quot;\\b(\\w+)\\b&quot;; NSString *replacedString = NULL; replacedString = [searchString stringByReplacingOccurrencesOfRegex:regexString usingBlock: ^NSString *(NSInteger captureCount, NSString * const capturedStrings, const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { return([NSString stringWithFormat:@&quot;{%@}&quot;, [capturedStrings[1] capitalizedString]]); }]; // 2010-04-14 21:00:42.726 test[35053:a0f] replaced string: &#39;{This} {Is} {Neat}.&#39;</div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:" class="code">- replaceOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">- replaceOccurrencesOfRegex:withString:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:" class="code">- stringByReplacingOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">- stringByReplacingOccurrencesOfRegex:withString:</a></li> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> </ul> </div> <h3>Splitting Strings</h3> <p>Strings can be split with a regular expression using the <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" title="Returns a NSArray containing substrings of the receiver that have been divided by the regular expression regex." class="code">componentsSeparatedByRegex:</a> methods. This functionality is nearly identical to the preexisting <span class="code">NSString</span> method <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:" class="code hardNobr">componentsSeparatedByString:</a>, except instead of only being able to use a fixed string as a separator, you can use a regular expression:</p> <div class="box sourcecode"><div>NSString *searchString <span class="hardNobr">= @&quot;This is neat.&quot;;</span> NSString *regexString <span class="hardNobr">= @&quot;\\s+&quot;;</span> NSArray *splitArray <span class="hardNobr">= NULL;</span> splitArray = <span class="hardNobr">[searchString</span> <span class="hardNobr">componentsSeparatedByRegex:regexString];</span> // <span class="comment">splitArray == { @&quot;This&quot;, @&quot;is&quot;, @&quot;neat.&quot; }</span> <span class="hardNobr">NSLog(@&quot;splitArray: %@&quot;,</span> <span class="hardNobr">splitArray);</span></div><div class="metainfo bottom noPrintBorder"><span class="entry continues below"><span class="item meta">Continues&hellip;</span></span></div><div class="floatRightPadder noSelect">&nbsp;</div></div> <p>The output from <span class="code">NSLog()</span> when run from a shell:</p> <div class="box shell"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;</span><span class="item info">splitArray</span></span></div><span class="shellOutput">shell% </span><span class="userInput">./splitArray<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2008-07-01 20:58:39.025 splitArray[69618:813] splitArray: ( This, is, &quot;neat.&quot; ) shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <p>Unfortunately our example string <span class="code">@&quot;This is neat.&quot;</span> doesn&#39;t allow us to show off the power of regular expressions. As you can probably imagine, splitting the string with the regular expression <span class="regex">\s+</span> allows for one or more <a href="#ICUSyntax_ICURegularExpressionSyntax_white_space" title="White space is defined as [\t\n\f\r\p{Z}]." class="regex-def">white space</a> characters to be matched. This can be much more flexible than just a fixed string of <span class="code hardNobr">@&quot;&nbsp;&quot;</span>, which will split on a single space only. If our example string contained extra spaces, say <span class="code hardNobr">@&quot;This&nbsp;&nbsp;&nbsp;is&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;neat.&quot;</span>, the result would have been the same.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">- componentsSeparatedByRegex:</a></li> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> </ul> </div> <h3>Creating an Array of Every Match</h3> <p><span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 3.0</span> adds several methods that conveniently perform a number of individual <span class="rkl">RegexKit<i>Lite</i></span> operations and aggregate the results in to a <span class="code">NSArray</span>. Since the result is a <span class="code">NSArray</span>, the standard Cocoa collection enumeration patterns can be used, such as <span class="code">NSEnumerator</span> and <span class="hardNobr">Objective-C 2.0&#39;s</span> <span class="hardNobr code">for&hellip;in</span> feature. One of the most common tasks is to extract all of the matches of a regular expression from a string. <span class="code">componentsMatchedByRegex:</span> returns the entire text matched by a regular expression even if the regular expression contains additional capture groups, effectively capture group <span class="code">0</span>. For example:</p> <div class="box sourcecode"><div>NSString *searchString = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSString *regexString = <span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;;</span> NSArray *matchArray = NULL; matchArray = [searchString componentsMatchedByRegex:regexString]; // <span class="comment">matchArray == { @&quot;$10.23&quot;, @&quot;$1024.42&quot;, @&quot;$3099&quot; };</span> <span class="hardNobr">NSLog(@&quot;matchArray: %@&quot;,</span> <span class="hardNobr">matchArray);</span></div><div class="metainfo bottom noPrintBorder"><span class="entry continues below"><span class="item meta">Continues&hellip;</span></span></div><div class="floatRightPadder noSelect">&nbsp;</div></div> <p>The output from <span class="code">NSLog()</span> when run from a shell:</p> <div class="box shell"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;</span><span class="item info">matchArray</span></span></div><span class="shellOutput">shell% </span><span class="userInput">./matchArray<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2009-05-06 03:20:03.546 matchArray[69939:10b] matchArray: ( &quot;$10.23&quot;, &quot;$1024.42&quot;, &quot;$3099&quot; ) shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <p>As the example above demonstrates, <span class="code">componentsMatchedByRegex:</span> returns the entire text that the regular expression matched even though the regular expression contains capture groups. <span class="code">arrayOfCaptureComponentsMatchedByRegex:</span> can be used if you need to get the text that the individual capture groups matched as well:</p> <div class="box sourcecode"><div>NSString *searchString = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSString *regexString = <span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;;</span> NSArray *capturesArray = NULL; capturesArray = [searchString arrayOfCaptureComponentsMatchedByRegex:regexString]; /* capturesArray == [NSArray arrayWithObjects: [NSArray arrayWithObjects: <span class="hardNobr">@&quot;$10.23&quot;,</span> <span class="hardNobr">@&quot;10.23&quot;,</span> <span class="hardNobr">@&quot;10&quot;,</span> <span class="hardNobr">@&quot;23&quot;,</span> <span class="hardNobr">NULL],</span> [NSArray arrayWithObjects:<span class="hardNobr">@&quot;$1024.42&quot;,</span> <span class="hardNobr">@&quot;1024.42&quot;,</span> <span class="hardNobr">@&quot;1024&quot;,</span> <span class="hardNobr">@&quot;42&quot;,</span> <span class="hardNobr">NULL],</span> [NSArray arrayWithObjects: <span class="hardNobr">@&quot;$3099&quot;,</span> <span class="hardNobr">@&quot;3099&quot;,</span> <span class="hardNobr">@&quot;3099&quot;,</span> <span class="hardNobr">@&quot;&quot;,</span> <span class="hardNobr">NULL],</span> NULL]; */ <span class="hardNobr">NSLog(@&quot;capturesArray: %@&quot;,</span> <span class="hardNobr">capturesArray);</span></div><div class="metainfo bottom noPrintBorder"><span class="entry continues below"><span class="item meta">Continues&hellip;</span></span></div><div class="floatRightPadder noSelect">&nbsp;</div></div> <p>The output from <span class="code">NSLog()</span> when run from a shell:</p> <div class="box shell"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;</span><span class="item info">capturesArray</span></span></div><span class="shellOutput">shell% </span><span class="userInput">./capturesArray<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2009-05-06 03:25:46.852 capturesArray[69981:10b] capturesArray: ( ( &quot;$10.23&quot;, &quot;10.23&quot;, 10, 23 ), ( &quot;$1024.42&quot;, &quot;1024.42&quot;, 1024, 42 ), ( &quot;$3099&quot;, 3099, 3099, &quot;&quot; ) ) shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:" class="code">- arrayOfCaptureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:" class="code">- captureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">- componentsMatchedByRegex:</a></li> <li><a href="#UsingRegexKitLite_EnumeratingMatches" class="section-link">Using <span class="rkl">RegexKit<i>Lite</i></span> - Enumerating Matches</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html" class="printURL section-link">Collections Programming Topics for Cocoa - Enumerators: Traversing a Collection&#39;s Elements</a></li> </ul> </div> <h3 id="UsingRegexKitLite_EnumeratingMatches">Enumerating Matches</h3> <p>The <span class="rkl">RegexKit<i>Lite</i></span> <span class="code">componentsMatchedByRegex:</span> method enables you to quickly create a <span class="code">NSArray</span> containing all the matches of a regular expression in a string. To enumerate the contents of the <span class="code">NSArray</span>, you can send the array an <span class="code">objectEnumerator</span> message.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">- componentsMatchedByRegex:</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html" class="printURL section-link">NSArray Class Reference</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSEnumerator_Class/Reference/Reference.html" class="printURL section-link">NSEnumerator Class Reference</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html" class="printURL section-link">Collections Programming Topics for Cocoa - Enumerators: Traversing a Collection&#39;s Elements</a></li> </ul> </div> <p style="margin-bottom: 0.5em;">An example using <span class="code">componentsMatchedByRegex:</span> and a <span class="code">NSEnumerator</span>:</p> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">main.m</span></span></div>#import &lt;Foundation/Foundation.h&gt; #import &quot;RegexKitLite.h&quot; int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *searchString = @&quot;one\ntwo\n\nfour\n&quot;; NSArray *matchArray = NULL; NSEnumerator *matchEnumerator = NULL; NSString *regexString = @&quot;(?m)^.*$&quot;; NSLog(@&quot;searchString: &#39;%@&#39;&quot;, searchString); NSLog(@&quot;regexString : &#39;%@&#39;&quot;, regexString); matchArray = [searchString componentsMatchedByRegex:regexString]; matchEnumerator = [matchArray objectEnumerator]; NSUInteger line = 0UL; NSString *matchedString = NULL; while((matchedString = [matchEnumerator nextObject]) != NULL) { NSLog(@&quot;%lu: %lu &#39;%@&#39;&quot;, <span class="hardNobr">(u_long)++line,</span> <span class="hardNobr">(u_long)[matchedString length],</span> <span class="hardNobr">matchedString);</span> } [pool release]; return(0); }</div> <p id="UsingRegexKitLite_EnumeratingMatches_exampleShellOutput">The following shell transcript demonstrates compiling the example and executing it. Line number three clearly demonstrates that matches of zero length are possible. Without the additional logic in <span class="code">nextObject</span> to handle this special case, the enumerator would never advance past the match.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>In the shell transcript below, the <span class="code hardNobr">NSLog()</span> line that prints <span class="code">searchString</span> has been annotated with the <span class="hardNobr">&#39;<span class="shellFont">&#9166;</span>&#39;</span> character to help visually identify the corresponding <span class="regex">\n</span> <span class="regex-def">new-line</span> characters in <span class="code">searchString</span>.</p> </div></div></div></div> <div class="box shell"><span class="shellOutput">shell% </span><span class="userInput">cd examples<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">shell% </span><span class="userInput">gcc -I.. -g -o main main.m <span class="hardNobr">../RegexKitLite.m</span> <span class="hardNobr">-framework Foundation</span> <span class="hardNobr">-licucore<span class="return" title="Return key">&crarr;</span></span></span> <span class="shellOutput">shell% </span><span class="userInput">./main<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2008-03-21 15:56:17.469 main[44050:807] searchString: &#39;one</span><span title="\n in searchString">&#9166;</span><span class="shellOutput"> two</span><span title="\n in searchString">&#9166;</span><span class="shellOutput">&#10;</span><span title="\n in searchString">&#9166;</span><span class="shellOutput"> four</span><span title="\n in searchString">&#9166;</span><span class="shellOutput"> &#39; 2008-03-21 15:56:17.520 main[44050:807] regexString : &#39;<span class="copyAsRegex">(?m)^.*$</span>&#39; 2008-03-21 15:56:17.575 main[44050:807] 1: 3 &#39;one&#39; 2008-03-21 15:56:17.580 main[44050:807] 2: 3 &#39;two&#39; 2008-03-21 15:56:17.584 main[44050:807] 3: 0 &#39;&#39; 2008-03-21 15:56:17.590 main[44050:807] 4: 4 &#39;four&#39; shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <h4>Enumerating Matches with Objective-C 2.0</h4> <p>You can enumerate all the matches of a regular expression in a string using <span class="hardNobr">Objective-C 2.0&#39;s</span> <span class="code hardNobr">for&hellip;in</span> feature. Compared to using a <span class="code">NSEnumerator</span>, using <span class="code hardNobr">for&hellip;in</span> not only takes fewer lines of code to accomplish the same thing, it is usually faster as well.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocFastEnumeration.html" class="printURL section-link">The Objective-C 2.0 Programming Language - Fast Enumeration</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html" class="printURL section-link">Collections Programming Topics for Cocoa - Enumerators: Traversing a Collection&#39;s Elements</a></li> </ul> </div> <p style="margin-bottom: 0.5em;">An example using the <span class="hardNobr">Objective-C 2.0</span> <span class="code hardNobr">for&hellip;in</span> feature:</p> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">for_in.m</span></span></div>#import &lt;Foundation/Foundation.h&gt; #import &quot;RegexKitLite.h&quot; int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *searchString = @&quot;one\ntwo\n\nfour\n&quot;; NSString *regexString = @&quot;(?m)^.*$&quot;; NSUInteger line = 0UL; NSLog(@&quot;searchString: &#39;%@&#39;&quot;, searchString); NSLog(@&quot;regexString : &#39;%@&#39;&quot;, regexString); for(NSString *matchedString in [searchString <span class="hardNobr">componentsMatchedByRegex:regexString]) {</span> NSLog(@&quot;%lu: %lu &#39;%@&#39;&quot;, <span class="hardNobr">(u_long)++line,</span> <span class="hardNobr">(u_long)[matchedString length],</span> <span class="hardNobr">matchedString);</span> } [pool release]; return(0); }</div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>The output of the preceding example is identical to the <span class="code">NSEnumerator</span> <a href="#UsingRegexKitLite_EnumeratingMatches_exampleShellOutput">shell output</a>.</p> </div></div></div></div> <h4>Enumerating Matches using Blocks</h4> A third way to enumerate all the matches of a regular expression in a string is to use one of the Blocks-based enumeration methods. <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:usingBlock:" class="code">- enumerateStringsMatchedByRegex:usingBlock:</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> An example using <span class="code">enumerateStringsMatchedByRegex:usingBlock:</span>: <!--%<div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">for\_in.m</span></span></div>--> <div class="box sourcecode">#import &lt;Foundation/Foundation.h&gt; #import &quot;RegexKitLite.h&quot; int main(int argc, char *argv) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *searchString = @&quot;one\ntwo\n\nfour\n&quot;; NSString *regexString = @&quot;(?m)^.*$&quot;; __block NSUInteger line = 0UL; NSLog(@&quot;searchString: &#39;%@&#39;&quot;, searchString); NSLog(@&quot;regexString : &#39;%@&#39;&quot;, regexString); [searchString enumerateStringsMatchedByRegex:regexString usingBlock: ^(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { NSLog(@&quot;%lu: %lu &#39;%@&#39;&quot;, ++line, [capturedStrings[0] length], capturedStrings[0]); }]; [pool release]; return(0); }</div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>The output of the preceding example is identical to the <span class="code">NSEnumerator</span> <a href="#UsingRegexKitLite_EnumeratingMatches_exampleShellOutput">shell output</a>.</p> </div></div></div></div> <h4 id="UsingRegexKitLite_DTrace">DTrace</h4> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>DTrace support is not enabled by default. To enable DTrace support, use the <span class="cpp_flag">RKL_DTRACE</span> pre-processor flag: <span class="consoleText">-DRKL_DTRACE</span></p> </div></div></div></div> <p><span class="rkl">RegexKit<i>Lite</i></span> has two DTrace probe points that provide information about its internal caches:</p> <ul class="square highlights"> <li><div class="signature" style="margin-top: 0.5em; margin-bottom: 0.5em;"><span class="hardNobr"><span class="function">RegexKitLite:::compiledRegexCache</span>(</span><span class="hardNobr">unsigned long <span class="argument">eventID</span>,</span> <span class="hardNobr">const char *<span class="argument">regexUTF8</span>,</span> <span class="hardNobr">int <span class="argument">options</span>,</span> <span class="hardNobr">int <span class="argument">captures</span>,</span> <span class="hardNobr">int <span class="argument">hitMiss</span>,</span> <span class="hardNobr">int <span class="argument">icuStatusCode</span>,</span> <span class="hardNobr">const char *<span class="argument">icuErrorMessage</span>,</span> <span class="hardNobr">double *<span class="argument">hitRate</span>);</span></div></li> <li><div class="signature" style="margin-top: 0.5em; margin-bottom: 0.5em;"><span class="hardNobr"><span class="function">RegexKitLite:::utf16ConversionCache</span>(</span><span class="hardNobr">unsigned long <span class="argument">eventID</span>,</span> <span class="hardNobr">unsigned int <span class="argument">lookupResultFlags</span>,</span> <span class="hardNobr">double *<span class="argument">hitRate</span>,</span> <span class="hardNobr">const void *<span class="argument">string</span>,</span> <span class="hardNobr">unsigned long <span class="argument">NSRange_location</span>,</span> <span class="hardNobr">unsigned long <span class="argument">NSRange_length</span>,</span> <span class="hardNobr">long <span class="argument">length</span>);</span></div></li> </ul> <p>Each of the probe points supply information via a number of arguments that are accessible through the DTrace variables <span class="code">arg0</span> &hellip; <span class="code">arg</span><i>n</i>.</p> <p>The first argument, <span class="argument">eventID</span> via <span class="code">arg0</span>, is a unique event ID that is incremented each time the <span class="rkl">RegexKit<i>Lite</i></span> mutex lock is acquired. All the probes that fire while the mutex is held will share the same event ID. This can help if you are trying to correlate multiple events across different CPUs.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"><p>Most uses of the <span class="consoleText">dtrace</span> command require superuser privileges. The examples given here use <span class="consoleText">sudo</span> to execute <span class="consoleText">dtrace</span> as the <span class="consoleText">root</span> user.</p></div></div></div></div> <p>The following is available in <span class="file">examples/compiledRegexCache.d</span> and demonstrates the use of all the arguments available via the <span class="code">RegexKitLite:::compiledRegexCache</span> probe point:</p> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">compiledRegexCache.d</span></span></div>#!/usr/sbin/dtrace -s RegexKitLite*:::compiledRegexCache { this-&gt;eventID = (unsigned long)arg0; this-&gt;regexUTF8 = copyinstr(arg1); this-&gt;options = (unsigned int)arg2; this-&gt;captures = (int)arg3; this-&gt;hitMiss = (int)arg4; this-&gt;icuStatusCode = (int)arg5; this-&gt;icuErrorMessage = (arg6 == 0) ? &quot;&quot; : copyinstr(arg6); this-&gt;hitRate = (double *)copyin(arg7, sizeof(double)); printf(&quot;%5d: %-60.60s Opt: %#8.8x Cap: %2d Hit: %2d Rate: %6.2f%% code: %5d msg: %s\n&quot;, this-&gt;eventID, this-&gt;regexUTF8, this-&gt;options, this-&gt;captures, this-&gt;hitMiss, *this-&gt;hitRate, this-&gt;icuStatusCode, this-&gt;icuErrorMessage); }</div> <p>Below is an example of the output, which has been trimmed for brevity, from <span class="file">compiledRegexCache.d</span>:</p> <div class="box shell"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;</span><span class="item info">compiledRegexCache.d</span></span></div><span class="shellOutput">shell% </span><span class="userInput">sudo dtrace -Z -q -s compiledRegexCache.d<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput"> 110: (\[{2})(.+?)(]{2}) Opt: 0x00000000 Cap: 3 Hit: 0 Rate: 63.64% code: 0 msg: 111: (\[{2})(.+?)(]{2}) Opt: 0x00000000 Cap: 3 Hit: 1 Rate: 63.96% code: 0 msg: 131: (\w+ Opt: 0x00000000 Cap: -1 Hit: -1 Rate: 63.36% code: 66310 msg: U_REGEX_MISMATCHED_PAREN 164: \b\s* Opt: 0x00000000 Cap: 0 Hit: 0 Rate: 60.98% code: 0 msg: 165: \$((\d+)(?:\.(\d+)|\.?)) Opt: 0x00000000 Cap: 3 Hit: 1 Rate: 61.21% code: 0 msg: 166: \b(https?)://([a-zA-Z0-9\-.]+)((?:/[a-zA-Z0-9\-._?,&#39;+\&amp;%$&hellip; Opt: 0x00000000 Cap: 3 Hit: 0 Rate: 60.84% code: 0 msg: shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <p>An example that prints the number of times that a compiled regular expression was not in the cache per second:</p> <div class="box shell"><span class="shellOutput">shell% </span><span class="userInput">sudo dtrace -Z -q -n &#39;RegexKitLite*:::compiledRegexCache /arg4 == 0/ { @miss[pid, execname] = count(); }&#39; -n &#39;tick-1sec { printa(&quot;%-8d %-40s %@d/sec\n&quot;, @miss); trunc(@miss); }&#39;<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">67003 RegexKitLite_tests 16/sec 67008 RegexKitLite_tests 50/sec</span> <span class="userInput">^C</span> <span class="shellOutput"> shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#DTrace_RegexKitLiteProbePoints__compiledRegexCache" class="code">RegexKitLite:::compiledRegexCache</a></li> <li><a href="http://docs.sun.com/app/docs/doc/817-6223" class="section-link printURL">Solaris Dynamic Tracing Guide</a> <a href="http://dlc.sun.com/pdf/817-6223/817-6223.pdf" class="section-link printURL">(as .PDF)</a></li> </ul> </div> <p>The following is available in <span class="file">examples/utf16ConversionCache.d</span> and demonstrates the use of all the arguments available via the <span class="code">RegexKitLite:::utf16ConversionCache</span> probe point.</p> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">utf16ConversionCache.d</span></span></div>#!/usr/sbin/dtrace -s enum { RKLCacheHitLookupFlag = 1 &lt;&lt; 0, RKLConversionRequiredLookupFlag = 1 &lt;&lt; 1, RKLSetTextLookupFlag = 1 &lt;&lt; 2, RKLDynamicBufferLookupFlag = 1 &lt;&lt; 3, RKLErrorLookupFlag = 1 &lt;&lt; 4 }; RegexKitLite*:::utf16ConversionCache { this-&gt;eventID = (unsigned long)arg0; this-&gt;lookupResultFlags = (unsigned int)arg1; this-&gt;hitRate = (double *)copyin(arg2, sizeof(double)); this-&gt;stringPtr = (void *)arg3; this-&gt;NSRange_location = (unsigned long)arg4; this-&gt;NSRange_length = (unsigned long)arg5; this-&gt;length = (long)arg6; printf(&quot;%5lu: flags: %#8.8x {Hit: %d Conv: %d SetText: %d Dyn: %d Error: %d} rate: %6.2f%% string: %#8.8p NSRange {%6lu, %6lu} length: %ld\n&quot;, this-&gt;eventID, this-&gt;lookupResultFlags, (this-&gt;lookupResultFlags &amp; RKLCacheHitLookupFlag) != 0, (this-&gt;lookupResultFlags &amp; RKLConversionRequiredLookupFlag) != 0, (this-&gt;lookupResultFlags &amp; RKLSetTextLookupFlag) != 0, (this-&gt;lookupResultFlags &amp; RKLDynamicBufferLookupFlag) != 0, (this-&gt;lookupResultFlags &amp; RKLErrorLookupFlag) != 0, *this-&gt;hitRate, this-&gt;stringPtr, this-&gt;NSRange_location, this-&gt;NSRange_length, this-&gt;length); }</div> <p>Below is an example of the output, which has been trimmed for brevity, from <span class="file">utf16ConversionCache.d</span>:</p> <div class="box shell"><div class="metainfo noPrintBorder"><span class="entry continues above"><span class="item meta">&hellip;</span><span class="item info">utf16ConversionCache.d</span></span></div><span class="shellOutput">shell% </span><span class="userInput">sudo dtrace -Z -q -s utf16ConversionCache.d<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput"> 85: flags: 0x00000000 {Hit: 0 Conv: 0 SetText: 0 Dyn: 0 Error: 0} rate: 59.18% string: 0x0010f530 NSRange { 0, 18} length: 18 86: flags: 0x00000004 {Hit: 0 Conv: 0 SetText: 1 Dyn: 0 Error: 0} rate: 59.18% string: 0x0010f530 NSRange { 0, 18} length: 18 87: flags: 0x00000006 {Hit: 0 Conv: 1 SetText: 1 Dyn: 0 Error: 0} rate: 58.00% string: 0x00054930 NSRange { 1, 37} length: 39 88: flags: 0x00000003 {Hit: 1 Conv: 1 SetText: 0 Dyn: 0 Error: 0} rate: 58.82% string: 0x00054930 NSRange { 1, 37} length: 39 109: flags: 0x00000006 {Hit: 0 Conv: 1 SetText: 1 Dyn: 0 Error: 0} rate: 53.62% string: 0x00054d00 NSRange { 0, 56} length: 56 110: flags: 0x00000006 {Hit: 0 Conv: 1 SetText: 1 Dyn: 0 Error: 0} rate: 52.86% string: 0x00054680 NSRange { 0, 1064} length: 1064 111: flags: 0x00000007 {Hit: 1 Conv: 1 SetText: 1 Dyn: 0 Error: 0} rate: 53.52% string: 0x00054680 NSRange { 46, 978} length: 1064 shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <p>An example that prints the number of times that a string required a conversion to <span class="hardNobr code">UTF-16</span> and was not in the cache per second:</p> <div class="box shell"><span class="shellOutput">shell% </span><span class="userInput">sudo dtrace -Z -q -n &#39;RegexKitLite*:::utf16ConversionCache /(arg1 &amp; 0x3) == 0x2/ { @miss[pid, execname] = count(); }&#39; -n &#39;tick-1sec { printa(&quot;%-8d %-40s %@d/sec\n&quot;, @miss); trunc(@miss); }&#39;<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">67020 RegexKitLite_tests 73/sec 67037 RegexKitLite_tests 64/sec</span> <span class="userInput">^C</span> <span class="shellOutput"> shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#DTrace_RegexKitLiteProbePoints__utf16ConversionCache" class="code">RegexKitLite:::utf16ConversionCache</a></li> <li><a href="#dtrace_utf16ConversionCache_lookupResultFlags" class="section-link">RegexKitLite:::utf16ConversionCache arg1 Flags</a></li> <li><a href="http://docs.sun.com/app/docs/doc/817-6223" class="section-link printURL">Solaris Dynamic Tracing Guide</a> <a href="http://dlc.sun.com/pdf/817-6223/817-6223.pdf" class="section-link printURL">(as .PDF)</a></li> </ul> </div> </div> <div class="printPageBreakAfter"> <h2 id="ICUSyntax">ICU Syntax</h2> <p>In this section:</p> <ul class="overview"> <li><a href="#ICUSyntax_ICURegularExpressionSyntax">ICU Regular Expression Syntax</a></li> <li><a href="#ICUSyntax_ICURegularExpressionCharacterClasses">ICU Regular Expression Character Classes</a></li> <li><a href="#ICUSyntax_UnicodeProperties">Unicode Properties</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax">ICU Replacement Text Syntax</a></li> </ul> <h3 id="ICUSyntax_ICURegularExpressionSyntax">ICU Regular Expression Syntax</h3> <p>For your convenience, the regular expression syntax from the ICU documentation is included below. When in doubt, you should refer to the official <a href="http://userguide.icu-project.org/strings/regexp" class="section-link NBSP_printURL">ICU User Guide - Regular Expressions</a> documentation page.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://userguide.icu-project.org/strings/regexp" class="section-link printURL">ICU User Guide - Regular Expressions</a></li> <li><a href="http://www.unicode.org/reports/tr18/" class="section-link printURL">Unicode Technical Standard #18 - Unicode Regular Expressions</a></li> </ul> </div> <div class="table regexSyntax"><div class="row"><div class="cell metacharacters"> <table class="regexSyntax" summary="Regular Expression Metacharacters"><caption>Metacharacters</caption> <tr><th>Character</th><th>Description</th></tr> <tr><td><span class="regex">\a</span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">BELL</span>, <span class="consoleText">\u0007</span></td></tr> <tr><td><span class="regex">\A</span></td><td>Match at the beginning of the input. Differs from <span class="regex">^</span> in that <span class="regex">\A</span> will not match after a <span class="regex-def">new-line</span> within the input.</td></tr> <tr><td><span class="regex">\b</span>, outside of a <span class="hardNobr"><span class="regex">[</span><i>Set</i><span class="regex">]</span></span></td> <td>Match if the current position is a word boundary. Boundaries occur at the transitions between <span class="regex-def">word</span> <span class="regex">\w</span> and <span class="regex-def">non-word</span> <span class="regex">\W</span> characters, with combining marks ignored.<div style="margin-top: 3px; margin-bottom: 2px;"><span class="hardNobr highlight"><b>See also:</b> <a href="#RKLRegexOptions_RKLUnicodeWordBoundaries" class="code">RKLUnicodeWordBoundaries</a></span></div></td></tr> <tr><td><span class="regex">\b</span>, within a <span class="hardNobr"><span class="regex">[</span><i>Set</i><span class="regex">]</span></span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">BACKSPACE</span>, <span class="consoleText">\u0008</span>.</td></tr> <tr><td><span class="regex">\B</span></td><td>Match if the current position is not a <span class="regex-def">word</span> boundary.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\c</span><i>x</i></span></td><td>Match a <span class="hardNobr"><i title="Control Character x, i.e. ^C">Control-x</i></span> character.</td></tr> <tr><td><span class="regex">\d</span></td><td>Match any character with the <i>Unicode General Category</i> of <span class="consoleText" title="Unicode Property Name, \p{Nd}">Nd</span> (<i>Number</i>, <i>Decimal Digit</i>).</td></tr> <tr><td><span class="regex">\D</span></td><td>Match any character that is not a <span class="regex-def">decimal digit</span>.</td></tr> <tr><td><span class="regex">\e</span></td><td>Match an <span class="unicodeCharName" title="Unicode Character Name">ESCAPE</span>, <span class="consoleText">\u001B</span>.</td></tr> <tr><td><span class="regex">\E</span></td><td>Terminates a <span class="hardNobr"><span class="regex">\Q</span><span title="Quoted Characters">&hellip;</span><span class="regex">\E</span></span> quoted sequence.</td></tr> <tr><td><span class="regex">\f</span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">FORM FEED</span>, <span class="consoleText">\u000C</span>.</td></tr> <tr><td><span class="regex">\G</span></td><td>Match if the current position is at the end of the previous match.</td></tr> <tr><td><span class="regex">\n</span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">LINE FEED</span>, <span class="consoleText">\u000A</span>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\N{</span><i>Unicode Character Name</i><span class="regex">}</span></span></td><td>Match the named <i>Unicode Character</i>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\p{</span><i>Unicode Property Name</i><span class="regex">}</span></span></td><td>Match any character with the specified <i>Unicode Property</i>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\P{</span><i>Unicode Property Name</i><span class="regex">}</span></span></td><td>Match any character not having the specified <i>Unicode Property</i>.</td></tr> <tr><td><span class="regex">\Q</span></td><td>Quotes all following characters until <span class="regex">\E</span>.</td></tr> <tr><td><span class="regex">\r</span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">CARRIAGE RETURN</span>, <span class="consoleText">\u000D</span>.</td></tr> <tr><td id="ICUSyntax_ICURegularExpressionSyntax_white_space"><span class="regex">\s</span></td><td>Match a <span class="regex-def">white space</span> character. White space is defined as <span class="regex">[\t\n\f\r\p{Z}]</span>.</td></tr> <tr><td><span class="regex">\S</span></td><td>Match a <span class="hardNobr">non-<span class="regex-def">white space</span></span> character.</td></tr> <tr><td><span class="regex">\t</span></td><td>Match a <span class="unicodeCharName" title="Unicode Character Name">HORIZONTAL TABULATION</span>, <span class="consoleText">\u0009</span>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\u</span><i>hhhh</i></span></td><td>Match the character with the hex value <i title="Hexidecimal Number">hhhh</i>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\U</span><i title="Hexidecimal Number">hhhhhhhh</i></span></td><td>Match the character with the hex value <i title="Hexidecimal Number">hhhhhhhh</i>. Exactly eight hex digits must be provided, even though the largest Unicode code point is <span class="consoleText">\U0010ffff</span>.</td></tr> <tr><td><span class="regex">\w</span></td><td>Match a word character. Word characters are <span class="regex">[\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}]</span>.</td></tr> <tr><td><span class="regex">\W</span></td><td>Match a <span class="hardNobr">non-word</span> character.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\x{</span><i title="Hexidecimal Number">h</i>&hellip;<span class="regex">}</span></span></td><td>Match the character with hex value <i title="Hexidecimal Number">hhhh</i>. From one to six hex digits may be supplied.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\x</span><i title="Hexidecimal Number">hh</i></span></td><td>Match the character with two digit hex value <i title="Hexidecimal Number">hh</i>.</td></tr> <tr><td><span class="regex">\X</span></td><td>Match a <a href="http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries" class="section-link printURL_small">Grapheme Cluster</a>.</td></tr> <tr><td><span class="regex">\Z</span></td><td>Match if the current position is at the end of input, but before the final line terminator, if one exists.</td></tr> <tr><td><span class="regex">\z</span></td><td>Match if the current position is at the end of input.</td></tr> <tr><td><span class="hardNobr"><span class="regex">\</span><i title="Decimal Number">n</i></span></td> <td> <div>Back Reference. Match whatever the <i title="Decimal Number">n</i>th capturing group matched. <i title="Decimal Number">n</i> must be a number &ge; 1 and &le; total number of capture groups in the pattern.</div> <div class="box small"><div><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell">Octal escapes, such as <span class="consoleText">\012</span>, are not supported.</div></div></div></div></div> </td></tr> <tr><td><span class="hardNobr"><span class="regex">[</span><i>pattern</i><span class="regex">]</span></span></td><td>Match any one character from the set. See <a href="#ICUSyntax_ICURegularExpressionCharacterClasses" class="section-link">ICU Regular Expression Character Classes</a> for a full description of what may appear in the pattern.</td></tr> <tr><td><span class="regex">.</span></td><td>Match any character.</td></tr> <tr><td><span class="regex">^</span></td><td>Match at the beginning of a line.</td></tr> <tr><td><span class="regex">$</span></td><td>Match at the end of a line.</td></tr> <tr><td><span class="regex">\</span></td><td>Quotes the following character. Characters that must be quoted to be treated as literals are <span class="consoleText">* ? + [ ( ) { } ^ $ | \ . /</span></td></tr> </table> </div><div class="cell operators"> <table class="regexSyntax" summary="Regular Expression Operators" id="ICUSyntax_Operators"><caption>Operators</caption> <tr><th>Operator</th><th>Description</th></tr> <tr><td><span class="regex">|</span></td><td>Alternation. <span class="regex">A|B</span> matches either <span class="regex">A</span> or <span class="regex">B</span>.</td></tr> <tr><td><span class="regex">*</span></td><td>Match zero or more times. Match as many times as possible.</td></tr> <tr><td><span class="regex">+</span></td><td>Match one or more times. Match as many times as possible.</td></tr> <tr><td><span class="regex">?</span></td><td>Match zero or one times. Prefer one.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">}</span></span></td><td>Match exactly <i title="Decimal Number">n</i> times.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,}</span></span></td><td>Match at least <i title="Decimal Number">n</i> times. Match as many times as possible.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,</span><i title="Decimal Number">m</i><span class="regex">}</span></span></td><td>Match between <i title="Decimal Number">n</i> and <i title="Decimal Number">m</i> times. Match as many times as possible, but not more than <i title="Decimal Number">m</i>.</td></tr> <tr><td><span class="regex">*?</span></td><td>Match zero or more times. Match as few times as possible.</td></tr> <tr><td><span class="regex">+?</span></td><td>Match one or more times. Match as few times as possible.</td></tr> <tr><td><span class="regex">??</span></td><td>Match zero or one times. Prefer zero.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">}?</span></span></td><td>Match exactly <i title="Decimal Number">n</i> times.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,}?</span></span></td><td>Match at least <i title="Decimal Number">n</i> times, but no more than required for an overall pattern match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,</span><i title="Decimal Number">m</i><span class="regex">}?</span></span></td><td>Match between <i title="Decimal Number">n</i> and <i title="Decimal Number">m</i> times. Match as few times as possible, but not less than <i title="Decimal Number">n</i>.</td></tr> <tr><td><span class="regex">*+</span></td><td>Match zero or more times. Match as many times as possible when first encountered, do not retry with fewer even if overall match fails. Possessive match.</td></tr> <tr><td><span class="regex">++</span></td><td>Match one or more times. Possessive match.</td></tr> <tr><td><span class="regex">?+</span></td><td>Match zero or one times. Possessive match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">}+</span></span></td><td>Match exactly <i title="Decimal Number">n</i> times. Possessive match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,}+</span></span></td><td>Match at least <i title="Decimal Number">n</i> times. Possessive match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">{</span><i title="Decimal Number">n</i><span class="regex">,</span><i title="Decimal Number">m</i><span class="regex">}+</span></span></td><td>Match between <i title="Decimal Number">n</i> and <i title="Decimal Number">m</i> times. Possessive match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Capturing parentheses. Range of input that matched the parenthesized subexpression is available after the match.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?:</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td><span class="hardNobr">Non-capturing</span> parentheses. Groups the included pattern, but does not provide capturing of matching text. Somewhat more efficient than capturing parentheses.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?&gt;</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Atomic-match parentheses. First match of the parenthesized subexpression is the only one tried; if it does not lead to an overall pattern match, back up the search for a match to a position before the <span class="regex">(?&gt;</span>&nbsp;.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?#</span><span title="Comment">&hellip;</span><span class="regex">)</span></span></td><td>Free-format comment <span class="hardNobr"><span class="regex">(?#</span><i>comment</i><span class="regex">)</span></span>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?=</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Look-ahead assertion. True if the parenthesized pattern matches at the current input position, but does not advance the input position.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?!</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Negative look-ahead assertion. True if the parenthesized pattern does not match at the current input position. Does not advance the input position.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?&lt;=</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Look-behind assertion. True if the parenthesized pattern matches text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no <span class="regex">*</span> or <span class="regex">+</span> operators).</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?&lt;!</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Negative Look-behind assertion. True if the parenthesized pattern does not match text preceding the current input position, with the last character of the match being the input character just before the current position. Does not alter the input position. The length of possible strings matched by the look-behind pattern must not be unbounded (no <span class="regex">*</span> or <span class="regex">+</span> operators).</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?ismwx-ismwx:</span><span title="Regular Expression">&hellip;</span><span class="regex">)</span></span></td><td>Flag settings. Evaluate the parenthesized expression with the specified flags <i>enabled</i> or <span class="hardNobr"><span class="regex">-</span><i>disabled</i></span>.</td></tr> <tr><td><span class="hardNobr"><span class="regex">(?ismwx-ismwx)</span></span></td><td>Flag settings. Change the flag settings. Changes apply to the portion of the pattern following the setting. For example, <span class="regex">(?i)</span> changes to a case insensitive match.<div style="margin-top: 2px; margin-bottom: 3px;"><span class="hardNobr highlight"><b>See also:</b> <a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></span></div></td></tr> </table> </div></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://userguide.icu-project.org/strings/regexp" class="section-link printURL">ICU User Guide - Regular Expressions</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> <h3 id="ICUSyntax_ICURegularExpressionCharacterClasses">ICU Regular Expression Character Classes</h3> <p>The following was originally from <a href="http://userguide.icu-project.org/strings/unicodeset" class="section-link">ICU User Guide - UnicodeSet</a>, but has been adapted to fit the needs of this documentation. Specifically, the ICU <span class="code">UnicodeSet</span> documentation describes an ICU C++ object&mdash; <span class="code">UnicodeSet</span>. The term <span class="code">UnicodeSet</span> was effectively replaced with <b>Character Class</b>, which is more appropriate in the context of regular expressions. As always, you should refer to the original, official documentation when in doubt.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://userguide.icu-project.org/strings/unicodeset" class="section-link printURL">ICU User Guide - UnicodeSet</a></li> <li><a href="http://www.unicode.org/reports/tr18/#Subtraction_and_Intersection" class="section-link printURL">UTS #18 Unicode Regular Expressions - Subtraction and Intersection</a></li> <li><a href="http://www.unicode.org/reports/tr18/#Categories" class="section-link printURL">UTS #18 Unicode Regular Expressions - Properties</a></li> </ul> </div> <h4>Overview</h4> <p>A character class is a regular expression pattern that represents a set of Unicode characters or character strings. The following table contains some example character class patterns:</p> <table class="regexSyntax"> <tr><th>Pattern</th><th>Description</th></tr> <tr><td><span class="regex">[a-z]</span></td><td>The lower case letters <span class="regexMatch">a</span> through <span class="regexMatch">z</span></td></tr> <tr><td><span class="regex">[abc123]</span></td><td>The six characters <span class="regexMatch">a</span>, <span class="regexMatch">b</span>, <span class="regexMatch">c</span>, <span class="regexMatch">1</span>, <span class="regexMatch">2</span>, and <span class="regexMatch">3</span></td></tr> <tr><td><span class="regex">[\p{Letter}]</span></td><td>All characters with the Unicode <span class="unicodeProperty">General Category</span> of <span class="unicodeProperty">Letter</span>.</td></tr> </table> <h5>String Values</h5> <p>In addition to being a set of Unicode code point characters, a character class may also contain string values. Conceptually, a character class is always a set of strings, not a set of characters. Historically, regular expressions have treated <span class="regex">[</span>&hellip;<span class="regex">]</span> character classes as being composed of single characters only, which is equivalent to a string that contains only a single character.</p> <h4>Character Class Patterns</h4> <p>Patterns are a series of characters bounded by square brackets that contain lists of characters and Unicode property sets. Lists are a sequence of characters that may have ranges indicated by a <span class="regex" title="Hyphen, dash, minus">-</span> between two characters, as in <span class="regex">a-z</span>. The sequence specifies the range of all characters from the left to the right, in Unicode order. For example, <span class="regex">[a c d-f m]</span> is equivalent to <span class="regex">[a c d e f m]</span>. Whitespace can be freely used for clarity as <span class="regex">[a c d-f m]</span> means the same as <span class="regex">[acd-fm]</span>.</p> <p>Unicode property sets are specified by a Unicode property, such as <span class="regex">[:Letter:]</span>. ICU version 2.0 supports <span class="unicodeProperty">General Category</span>, <span class="unicodeProperty">Script</span>, and <span class="unicodeProperty">Numeric Value</span> properties (ICU will support additional properties in the future). For a list of the property names, see the end of this section. The syntax for specifying the property names is an extension of either POSIX or Perl syntax with the addition of <span class="regex">=value</span>. For example, you can match letters by using the POSIX syntax <span class="regex">[:Letter:]</span>, or by using the Perl syntax <span class="regex">\p{Letter}</span>. The type can be omitted for the <span class="unicodeProperty">Category</span> and <span class="unicodeProperty">Script</span> properties, but is required for other properties.</p> <p>The following table lists the standard and negated forms for specifying Unicode properties in both POSIX or Perl syntax. The negated form specifies a character class that includes everything but the specified property. For example, <span class="regex">[:^Letter:]</span> matches all characters that are not <span class="regex">[:Letter:]</span>.</p> <table class="regexSyntax"> <tr><th>Syntax Style</th><th>Standard</th><th>Negated</th></tr> <tr><td>POSIX</td><td><span class="regex">[:</span><i>type=value</i><span class="regex">:]</span></td><td><span class="regex">[:^</span><i>type=value</i><span class="regex">:]</span></td></tr> <tr><td>Perl</td><td><span class="regex">\p{</span><i>type=value</i><span class="regex">}</span></td><td><span class="regex">\P{</span><i>type=value</i><span class="regex">}</span></td></tr> </table> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://www.unicode.org/reports/tr18/#Categories" class="section-link printURL">UTS #18 Unicode Regular Expressions - Properties</a></li> </ul> </div> <p>Character classes can then be modified using standard set operations&mdash; Union, Inverse, Difference, and Intersection.</p> <ul class="square"> <li><p>To union two sets, simply concatenate them. For example, <span class="regex">[[:letter:] [:number:]]</span></p></li> <li><p>To intersect two sets, use the <span class="regex">&amp;</span> operator. For example, <span class="regex">[[:letter:] &amp; [a-z]]</span></p></li> <li><p>To take the set-difference of two sets, use the <span class="regex" title="Hyphen, dash, minus">-</span> operator. For example, <span class="regex">[[:letter:] - [a-z]]</span></p></li> <li><p>To invert a set, place a <span class="regex" title="Caret, circumflex">^</span> immediately after the opening <span class="regex">[</span>. For example, <span class="regex">[^a-z]</span>. In any other location, the <span class="regex" title="Caret, circumflex">^</span> does not have a special meaning.</p></li> </ul> <p>The binary operators <span class="regex">&amp;</span> and <span class="regex" title="Hyphen, dash, minus">-</span> have equal precedence and bind left-to-right. Thus <span class="regex">[[:letter:]-[a-z]-[\u0100-\u01FF]]</span> is equivalent to <span class="regex">[[[:letter:]-[a-z]]-[\u0100-\u01FF]]</span>. Another example is the set <span class="regex">[[ace][bdf] - [abc][def]]</span> is <b>not</b> the empty set, but instead the set <span class="regex">[def]</span>. This only really matters for the difference operation, as the intersection operation is commutative.</p> <p>Another caveat with the <span class="regex">&amp;</span> and <span class="regex" title="Hyphen, dash, minus">-</span> operators is that they operate between <b>sets</b>. That is, they must be immediately preceded and immediately followed by a set. For example, the pattern <span class="regex">[[:Lu:]-A]</span> is illegal, since it is interpreted as the set <span class="regex">[:Lu:]</span> followed by the incomplete range <span class="regex">-A</span>. To specify the set of uppercase letters except for <span class="regex">A</span>, enclose the <span class="regex">A</span> in a set: <span class="regex">[[:Lu:]-[A]]</span>.</p> <table class="regexSyntax"> <tr><th>Pattern</th><th>Description</th></tr> <tr><td><span class="regex">[a]</span></td><td>The set containing <span class="regexMatch">a</span>.</td></tr> <tr><td><span class="regex">[a-z]</span></td><td>The set containing <span class="regexMatch">a</span> through <span class="regexMatch">z</span> and all letters in between, in Unicode order.</td></tr> <tr><td><span class="regex">[^a-z]</span></td><td>The set containing all characters but <span class="regexMatch">a</span> through <span class="regexMatch">z</span>, that is, <span class="code">U+0000</span> through <span class="code">a-1</span> and <span class="code">z+1</span> through <span class="code">U+FFFF</span>.</td></tr> <tr><td><span class="regex">[[</span><i>pat1</i><span class="regex">][</span><i>pat2</i><span class="regex">]]</span></td><td>The union of sets specified by <i>pat1</i> and <i>pat2</i>.</td></tr> <tr><td><span class="regex">[[</span><i>pat1</i><span class="regex">]&amp;[</span><i>pat2</i><span class="regex">]]</span></td><td>The intersection of sets specified by <i>pat1</i> and <i>pat2</i>.</td></tr> <tr><td><span class="regex">[[</span><i>pat1</i><span class="regex">]-[</span><i>pat2</i><span class="regex">]]</span></td><td>The asymmetric difference of sets specified by <i>pat1</i> and <i>pat2</i>.</td></tr> <tr><td><span class="regex">[:Lu:]</span></td><td>The set of characters belonging to the given Unicode category. In this case, Unicode uppercase letters. The long form for this is <span class="regex">[:UppercaseLetter:]</span>.</td></tr> <tr><td><span class="regex">[:L:]</span></td><td>The set of characters belonging to all Unicode categories starting with <span class="unicodeProperty">L</span>, that is, <span class="regex">[[:Lu:][:Ll:][:Lt:][:Lm:][:Lo:]]</span>. The long form for this is <span class="regex">[:Letter:]</span>.</td></tr> </table> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://www.unicode.org/reports/tr18/#Subtraction_and_Intersection" class="section-link printURL">UTS #18 Unicode Regular Expressions - Subtraction and Intersection</a></li> </ul> </div> <h5>String Values in Character Classes</h5> <p>String values are enclosed in <span class="regex">{</span><i>curly brackets</i><span class="regex">}</span>. For example:</p> <table class="regexSyntax"> <tr><th>Pattern</th><th>Description</th></tr> <tr><td><span class="regex">[abc{def}]</span></td><td>A set containing four members, the single characters <span class="regexMatch">a</span>, <span class="regexMatch">b</span>, and <span class="regexMatch">c</span> and the string <span class="regexMatch">def</span></td></tr> <tr><td><span class="regex">[{abc}{def}]</span></td><td>A set containing two members, the string <span class="regexMatch">abc</span> and the string <span class="regexMatch">def</span>.</td></tr> <tr><td><span class="regex">[{a}{b}{c}][abc]</span></td><td>These two sets are equivalent. Each contains three items, the three individual characters <span class="regexMatch">a</span>, <span class="regexMatch">b</span>, and <span class="regexMatch">c</span>. A <span class="regex">{</span><i>string</i><span class="regex">}</span> containing a single character is equivalent to that same character specified in any other way.</td></tr> </table> <h4>Character Quoting and Escaping in ICU Character Class Patterns</h4> <h5>Single Quote</h5> <p>Two single quotes represent a single quote, either inside or outside single quotes. Text within single quotes is not interpreted in any way, except for two adjacent single quotes. It is taken as literal text&mdash; special characters become non-special. These quoting conventions for ICU character classes differ from those of Perl or Java. In those environments, single quotes have no special meaning, and are treated like any other literal character.</p> <h5>Backslash Escapes</h5> <p>Outside of single quotes, certain backslashed characters have special meaning:</p> <table class="regexSyntax"> <tr><th>Pattern</th><th>Description</th></tr> <tr><td><span class="regex">\u</span><i title="Hexidecimal Number">hhhh</i></td><td>Exactly 4 hex digits; <i>h</i> in <span class="regex">[0-9A-Fa-f]</span></td></tr> <tr><td><span class="regex">\U</span><i title="Hexidecimal Number">hhhhhhhh</i></td><td>Exactly 8 hex digits</td></tr> <tr><td><span class="regex">\x</span><i title="Hexidecimal Number">hh</i></td><td>1-2 hex digits</td></tr> <tr><td><span class="regex">\</span><i>ooo</i></td><td>1-3 octal digits; <i>o</i> in <span class="regex">[0-7]</span></td></tr> <tr><td><span class="regex">\a</span></td><td><span class="code">U+0007</span> <span class="unicodeCharName" title="Unicode Character Name">BELL</span></td></tr> <tr><td><span class="regex">\b</span></td><td><span class="code">U+0008</span> <span class="unicodeCharName" title="Unicode Character Name">BACKSPACE</span></td></tr> <tr><td><span class="regex">\t</span></td><td><span class="code">U+0009</span> <span class="unicodeCharName" title="Unicode Character Name">HORIZONTAL TAB</span></td></tr> <tr><td><span class="regex">\n</span></td><td><span class="code">U+000A</span> <span class="unicodeCharName" title="Unicode Character Name">LINE FEED</span></td></tr> <tr><td><span class="regex">\v</span></td><td><span class="code">U+000B</span> <span class="unicodeCharName" title="Unicode Character Name">VERTICAL TAB</span></td></tr> <tr><td><span class="regex">\f</span></td><td><span class="code">U+000C</span> <span class="unicodeCharName" title="Unicode Character Name">FORM FEED</span></td></tr> <tr><td><span class="regex">\r</span></td><td><span class="code">U+000D</span> <span class="unicodeCharName" title="Unicode Character Name">CARRIAGE RETURN</span></td></tr> <tr><td><span class="regex">\\</span></td><td><span class="code">U+005C</span> <span class="unicodeCharName" title="Unicode Character Name">BACKSLASH</span></td></tr> </table> <p>Anything else following a backslash is mapped to itself, except in an environment where it is defined to have some special meaning. For example, <span class="regex">\p{Lu}</span> is the set of uppercase letters. Any character formed as the result of a backslash escape loses any special meaning and is treated as a literal. In particular, note that <span class="regex">\u</span> and <span class="regex">\U</span> escapes create literal characters.</p> <h5>Whitespace</h5> <p>Whitespace, as defined by the ICU API, is ignored unless it is quoted or backslashed.</p> <h4>Property Values</h4> <p>The following property value styles are recognized:</p> <table class="regexSyntax"> <tr><th>Style</th><th>Description</th></tr> <tr><td>Short</td><td>Omits the <span class="regex doNotEscape">=type</span> argument. Used to prevent ambiguity and only allowed with the <span class="unicodeProperty">Category</span> and <span class="unicodeProperty">Script</span> properties.</td></tr> <tr><td>Medium</td><td>Uses an abbreviated <span class="regex doNotEscape">type</span> and <span class="regex doNotEscape">value</span>.</td></tr> <tr><td>Long</td><td>Uses a full <span class="regex doNotEscape">type</span> and <span class="regex doNotEscape">value</span>.</td></tr> </table> <p>If the <span class="regex doNotCopy">type</span> or <span class="regex doNotCopy">value</span> is omitted, then the <span class="regex doNotCopy">=</span> equals sign is also omitted. The short style is only used for <span class="unicodeProperty">Category</span> and <span class="unicodeProperty">Script</span> properties because these properties are very common and their omission is unambiguous.</p> <p>In actual practice, you can mix <span class="regex doNotCopy">type</span> names and <span class="regex doNotCopy">values</span> that are omitted, abbreviated, or full. For example, if <span class="unicodeProperty">Category=Unassigned</span> you could use what is in the table explicitly, <span class="regex">\p{gc=Unassigned}</span>, <span class="regex">\p{Category=Cn}</span>, or <span class="regex">\p{Unassigned}</span>.</p> <p>When these are processed, case and whitespace are ignored so you may use them for clarity, if desired. For example, <span class="regex">\p{Category = Uppercase Letter}</span> or <span class="regex">\p{Category = uppercase letter}</span>.</p> <p>For a list of properties supported by ICU, see <a href="http://userguide.icu-project.org/strings/properties" class="section-link printURL">ICU User Guide - Unicode Properties</a>.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://userguide.icu-project.org/strings/properties" class="section-link printURL">ICU User Guide - Unicode Properties</a></li> <li><a href="http://www.unicode.org/reports/tr18/#Categories" class="section-link printURL">UTS #18 Unicode Regular Expressions - Properties</a></li> </ul> </div> <h3 id="ICUSyntax_UnicodeProperties">Unicode Properties</h3> <p>The following tables list some of the commonly used Unicode Properties, which can be matched in a regular expression with <span class="regex">\p{</span><i>Property</i><span class="regex">}</span>. The tables were created from the <a href="http://www.unicode.org/versions/Unicode5.2.0/" class="hardNobr">Unicode 5.2</a> Unicode Character Database, which is the version used by ICU that ships with <span class="hardNobr">Mac OS X 10.6</span>.</p> <div class="table" style="margin-top: 1em; margin-bottom: 1em;"><div class="row"><div class="cell"> <table class="regexSyntax unicodeProperties"> <tr><th colspan="2">Category</th></tr> <tr><td class="consoleText">L</td><td class="consoleText">Letter</td></tr> <tr><td class="consoleText">LC</td><td class="consoleText">CasedLetter</td></tr> <tr><td class="consoleText">Lu</td><td class="consoleText">UppercaseLetter</td></tr> <tr><td class="consoleText">Ll</td><td class="consoleText">LowercaseLetter</td></tr> <tr><td class="consoleText">Lt</td><td class="consoleText">TitlecaseLetter</td></tr> <tr><td class="consoleText">Lm</td><td class="consoleText">ModifierLetter</td></tr> <tr><td class="consoleText">Lo</td><td class="consoleText">OtherLetter</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">P</td><td class="consoleText">Punctuation</td></tr> <tr><td class="consoleText">Pc</td><td class="consoleText">ConnectorPunctuation</td></tr> <tr><td class="consoleText">Pd</td><td class="consoleText">DashPunctuation</td></tr> <tr><td class="consoleText">Ps</td><td class="consoleText">OpenPunctuation</td></tr> <tr><td class="consoleText">Pe</td><td class="consoleText">ClosePunctuation</td></tr> <tr><td class="consoleText">Pi</td><td class="consoleText">InitialPunctuation</td></tr> <tr><td class="consoleText">Pf</td><td class="consoleText">FinalPunctuation</td></tr> <tr><td class="consoleText">Po</td><td class="consoleText">OtherPunctuation</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">N</td><td class="consoleText">Number</td></tr> <tr><td class="consoleText">Nd</td><td class="consoleText">DecimalNumber</td></tr> <tr><td class="consoleText">Nl</td><td class="consoleText">LetterNumber</td></tr> <tr><td class="consoleText">No</td><td class="consoleText">OtherNumber</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">M</td><td class="consoleText">Mark</td></tr> <tr><td class="consoleText">Mn</td><td class="consoleText">NonspacingMark</td></tr> <tr><td class="consoleText">Mc</td><td class="consoleText">SpacingMark</td></tr> <tr><td class="consoleText">Me</td><td class="consoleText">EnclosingMark</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">S</td><td class="consoleText">Symbol</td></tr> <tr><td class="consoleText">Sm</td><td class="consoleText">MathSymbol</td></tr> <tr><td class="consoleText">Sc</td><td class="consoleText">CurrencySymbol</td></tr> <tr><td class="consoleText">Sk</td><td class="consoleText">ModifierSymbol</td></tr> <tr><td class="consoleText">So</td><td class="consoleText">OtherSymbol</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">Z</td><td class="consoleText">Separator</td></tr> <tr><td class="consoleText">Zs</td><td class="consoleText">SpaceSeparator</td></tr> <tr><td class="consoleText">Zl</td><td class="consoleText">LineSeparator</td></tr> <tr><td class="consoleText">Zp</td><td class="consoleText">ParagraphSeparator</td></tr> <tr><td class="consoleText" colspan="2">&nbsp;</td></tr> <tr><td class="consoleText">C</td><td class="consoleText">Other</td></tr> <tr><td class="consoleText">Cc</td><td class="consoleText">Control</td></tr> <tr><td class="consoleText">Cf</td><td class="consoleText">Format</td></tr> <tr><td class="consoleText">Cs</td><td class="consoleText">Surrogate</td></tr> <tr><td class="consoleText">Co</td><td class="consoleText">PrivateUse</td></tr> <tr><td class="consoleText">Cn</td><td class="consoleText">Unassigned</td></tr> </table> </div><div class="cell" style="max-width: 4.2in"> <table class="regexSyntax unicodeProperties" style="width: 100%;"> <tr><th colspan="3">Script</th></tr> <tr><td class="consoleText" style="width: 33%;">Arabic</td><td class="consoleText" style="width: 33%;">Armenian</td><td class="consoleText" style="width: 33%;">Balinese</td></tr> <tr><td class="consoleText">Bengali</td><td class="consoleText">Bopomofo</td><td class="consoleText">Braille</td></tr> <tr><td class="consoleText">Buginese</td><td class="consoleText">Buhid</td><td class="consoleText softNobr"><span><span class="tbrOn">Canadian_&#8203;Aboriginal</span><span class="tbrOff">Canadian_Aboriginal</span></span></td></tr> <tr><td class="consoleText">Carian</td><td class="consoleText">Cham</td><td class="consoleText">Cherokee</td></tr> <tr><td class="consoleText">Common</td><td class="consoleText">Coptic</td><td class="consoleText">Cuneiform</td></tr> <tr><td class="consoleText">Cypriot</td><td class="consoleText">Cyrillic</td><td class="consoleText">Deseret</td></tr> <tr><td class="consoleText">Devanagari</td><td class="consoleText">Ethiopic</td><td class="consoleText">Georgian</td></tr> <tr><td class="consoleText">Glagolitic</td><td class="consoleText">Gothic</td><td class="consoleText">Greek</td></tr> <tr><td class="consoleText">Gujarati</td><td class="consoleText">Gurmukhi</td><td class="consoleText">Han</td></tr> <tr><td class="consoleText">Hangul</td><td class="consoleText">Hanunoo</td><td class="consoleText">Hebrew</td></tr> <tr><td class="consoleText">Hiragana</td><td class="consoleText">Inherited</td><td class="consoleText">Kannada</td></tr> <tr><td class="consoleText">Katakana</td><td class="consoleText">Kayah_Li</td><td class="consoleText">Kharoshthi</td></tr> <tr><td class="consoleText">Khmer</td><td class="consoleText">Lao</td><td class="consoleText">Latin</td></tr> <tr><td class="consoleText">Lepcha</td><td class="consoleText">Limbu</td><td class="consoleText">Linear_B</td></tr> <tr><td class="consoleText">Lycian</td><td class="consoleText">Lydian</td><td class="consoleText">Malayalam</td></tr> <tr><td class="consoleText">Mongolian</td><td class="consoleText">Myanmar</td><td class="consoleText">New_Tai_Lue</td></tr> <tr><td class="consoleText">Nko</td><td class="consoleText">Ogham</td><td class="consoleText">Ol_Chiki</td></tr> <tr><td class="consoleText">Old_Italic</td><td class="consoleText">Old_Persian</td><td class="consoleText">Oriya</td></tr> <tr><td class="consoleText">Osmanya</td><td class="consoleText">Phags_Pa</td><td class="consoleText">Phoenician</td></tr> <tr><td class="consoleText">Rejang</td><td class="consoleText">Runic</td><td class="consoleText">Saurashtra</td></tr> <tr><td class="consoleText">Shavian</td><td class="consoleText">Sinhala</td><td class="consoleText">Sundanese</td></tr> <tr><td class="consoleText">Syloti_Nagri</td><td class="consoleText">Syriac</td><td class="consoleText">Tagalog</td></tr> <tr><td class="consoleText">Tagbanwa</td><td class="consoleText">Tai_Le</td><td class="consoleText">Tamil</td></tr> <tr><td class="consoleText">Telugu</td><td class="consoleText">Thaana</td><td class="consoleText">Thai</td></tr> <tr><td class="consoleText">Tibetan</td><td class="consoleText">Tifinagh</td><td class="consoleText">Ugaritic</td></tr> <tr><td class="consoleText">Unknown</td><td class="consoleText">Vai</td><td class="consoleText">Yi</td></tr> </table> <table class="regexSyntax unicodeProperties" style="margin-top: 2em; width: 100%;"> <tr><th colspan="2">Extended Property Class</th></tr> <tr><td class="consoleText">ASCII_Hex_Digit</td><td class="consoleText">Alphabetic</td></tr> <tr><td class="consoleText">Bidi_Control</td><td class="consoleText">Dash</td></tr> <tr><td class="consoleText softNobr"><span><span class="tbrOn">Default_&#8203;Ignorable_&#8203;Code_&#8203;Point</span><span class="tbrOff">Default_Ignorable_Code_Point</span></span></td><td class="consoleText">Deprecated</td></tr> <tr><td class="consoleText">Diacritic</td><td class="consoleText">Extender</td></tr> <tr><td class="consoleText">Grapheme_Base</td><td class="consoleText">Grapheme_Extend</td></tr> <tr><td class="consoleText">Grapheme_Link</td><td class="consoleText">Hex_Digit</td></tr> <tr><td class="consoleText">Hyphen</td><td class="consoleText softNobr"><span><span class="tbrOn">IDS_&#8203;Binary_&#8203;Operator</span><span class="tbrOff">IDS_Binary_Operator</span></span></td></tr> <tr><td class="consoleText">IDS_Trinary_Operator</td><td class="consoleText">ID_Continue</td></tr> <tr><td class="consoleText">ID_Start</td><td class="consoleText">Ideographic</td></tr> <tr><td class="consoleText">Join_Control</td><td class="consoleText softNobr"><span><span class="tbrOn">Logical_&#8203;Order_&#8203;Exception</span><span class="tbrOff">Logical_Order_Exception</span></span></td></tr> <tr><td class="consoleText">Lowercase</td><td class="consoleText">Math</td></tr> <tr><td class="consoleText">Noncharacter_Code_Point</td><td class="consoleText">Other_Alphabetic</td></tr> <tr><td class="consoleText softNobr"><span><span class="tbrOn">Other_&#8203;Default_&#8203;Ignorable_&#8203;Code_&#8203;Point</span><span class="tbrOff">Other_Default_Ignorable_Code_Point</span></span></td><td class="consoleText softNobr"><span><span class="tbrOn">Other_&#8203;Grapheme_&#8203;Extend</span><span class="tbrOff">Other_Grapheme_Extend</span></span></td></tr> <tr><td class="consoleText">Other_ID_Continue</td><td class="consoleText">Other_ID_Start</td></tr> <tr><td class="consoleText">Other_Lowercase</td><td class="consoleText">Other_Math</td></tr> <tr><td class="consoleText">Other_Uppercase</td><td class="consoleText">Pattern_Syntax</td></tr> <tr><td class="consoleText">Pattern_White_Space</td><td class="consoleText">Quotation_Mark</td></tr> <tr><td class="consoleText">Radical</td><td class="consoleText">STerm</td></tr> <tr><td class="consoleText">Soft_Dotted</td><td class="consoleText softNobr"><span><span class="tbrOn">Terminal_&#8203;Punctuation</span><span class="tbrOff">Terminal_Punctuation</span></span></td></tr> <tr><td class="consoleText">Unified_Ideograph</td><td class="consoleText">Uppercase</td></tr> <tr><td class="consoleText">Variation_Selector</td><td class="consoleText">White_Space</td></tr> <tr><td class="consoleText">XID_Continue</td><td class="consoleText">XID_Start</td></tr> </table> </div></div></div> <h4>Unicode Character Database</h4> <p>Unicode properties are defined in the <a href="http://www.unicode.org/ucd/">Unicode Character Database</a>, or <span class="new-term">UCD</span>. From time to time the UCD is <a href="http://www.unicode.org/versions/">revised and updated</a>. The properties available, and the definition of the characters they match, depend on the UCD that ICU was built with.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>In general, the ICU and UCD versions change with each major operating system release.</p> </div></div></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://www.unicode.org/reports/tr18/#Categories" class="section-link printURL">UTS #18 Unicode Regular Expressions - Properties</a></li> <li><a href="http://www.unicode.org/reports/tr18/#Compatibility_Properties" class="section-link printURL">UTS #18 Unicode Regular Expressions - Compatibility Properties</a></li> <li><a href="http://www.unicode.org/ucd/" class="section-link printURL">Unicode Character Database</a></li> <li><a href="http://www.unicode.org/versions/Unicode5.2.0/" class="section-link printURL">The Unicode Standard - Unicode 5.2</a></li> <li><a href="http://www.unicode.org/versions/" class="section-link printURL">Versions of the Unicode Standard</a></li> </ul> </div> <h3 id="ICUSyntax_ICUReplacementTextSyntax">ICU Replacement Text Syntax</h3> <div class="table regexSyntax"> <table class="regexSyntax" summary="Replacement Text Syntax"><caption>Replacement Text Syntax</caption> <tr><th>Character</th><th>Description</th></tr> <tr><td><span class="regex">$</span><i title="Decimal Number">n</i></td><td><div>The text of capture group <i title="Decimal Number">n</i> will be substituted for <span class="regex">$</span><i title="Decimal Number">n</i>. <i title="Decimal Number">n</i> must be &ge; <span class="consoleText">0</span> and not greater than the number of capture groups. A <span class="regex">$</span> not followed by a digit has no special meaning, and will appear in the substitution text as itself, a <span class="regex">$</span>.</div> <div class="box small"><div><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Methods will raise a <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <i title="Decimal Number">n</i> is greater than the number of capture groups in the regular expression.</div></div></div></div></div> </td></tr> <tr><td><span class="regex">\</span></td><td>Treat the character following the backslash as a literal, suppressing any special meaning. Backslash escaping in substitution text is only required for <span class="regex">$</span> and <span class="regex">\</span>, but may proceed any character. The backslash itself will not be copied to the substitution text.</td></tr> </table> </div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://userguide.icu-project.org/strings/regexp#TOC-Replacement-Text" class="section-link printURL">ICU User Guide - Replacement Text</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:options:range:error:" class="code">- replaceOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:options:range:error:" class="code">- stringByReplacingOccurrencesOfRegex:withString:options:range:error:</a></li> </ul> </div> </div> <div class="printPageBreakAfter"> <h2 id="RegexKitLiteCookbook"><span class="rkl">RegexKit<i>Lite</i></span> Cookbook</h2> <table class="quotation"> <tr><td class="quote">Some people, when confronted with a problem, think &ldquo;I know, I&#39;ll use regular expressions.&rdquo; Now they have two problems.</td></tr> <tr><td class="attribution">Jamie Zawinski</td></tr> </table> <p>This section contains a collection of regular expressions and example code demonstrating how <span class="rkl">RegexKit<i>Lite</i></span> makes some common programming choirs easier. <span class="rkl">RegexKit<i>Lite</i></span> makes it easy to match part of a string and extract just that part, or even create an entirely new string using just a few pieces of the original string. A great example of this is a string that contains a URL and you need to extract just a part of it, perhaps the host or maybe just the port used. This example demonstrates how easy it is to extract the port used from a URL, which is then converted in to a <span class="code">NSInteger</span> value:</p> <div class="box sourcecode">searchString = @&quot;http://www.example.com:8080/index.html&quot;; regexString = @&quot;\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,&#39;+\\&amp;%$=~*!():@\\\\]*)+)?&quot;; NSInteger portInteger = [[searchString stringByMatching:regexString capture:1L] integerValue]; NSLog(@&quot;portInteger: &#39;%ld&#39;&quot;, (long)portInteger); // <span class="comment">2008-10-15 08:52:52.500 host_port[8021:807] portInteger: &#39;8080&#39;</span></div> <p>Inside you&#39;ll find more examples like this that you can use as the starting point for your own regular expression pattern matching solution. Keep in mind that these are meant to be examples to help get you started and not necessarily the ideal solution for every need. Trade&#8209;offs are usually made when creating a regular expression, matching an email address is a perfect example of this. A regular expression that precisely matches the formal definition of email address is both complicated and usually unnecessary. Knowing which trade&#8209;offs are acceptable requires that you understand what it is you&#39;re trying to match, the data that you&#39;re searching through, and the requirements and uses of the matched results. It won&#39;t take long until you gain an appreciation for Jamie Zawinski&#39;s infamous quote.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://oreilly.com/catalog/9780596528126/" class="section-link printURL">O&#39;Reilly - Mastering Regular Expressions, 3rd edition by Jeffrey Friedl</a></li> <li><a href="http://regexlib.com/" class="section-link printURL">RegExLib.com - Regular Expression Library</a></li> <li><a href="http://userguide.icu-project.org/strings/regexp" class="section-link printURL">ICU Userguide - Regular Expressions</a></li> <li><a href="http://www.regular-expressions.info/" class="section-link printURL">Regular-Expressions.info - Regex Tutorial, Examples, and Reference</a></li> <li><a href="http://en.wikipedia.org/wiki/Regular_expression" class="section-link printURL">Wikipedia - Regular Expression</a></li> </ul> </div> <div class="enhancedCopyOnly screenOnly"> <h3>Enhanced Copy To Clipboard Functionality</h3> <div class="box titled copyToClipboard preferences UIpane screenOnly" id="copyRegexToClipboardPreferences"> <div class="title blueGrey">Copy Regex to Clipboard Preferences</div> <div class="contents alum2"> <div class="UItopTitleSpacer"> <div class="insetOuter"><div class="insetMiddle"><div class="inset"> <table class="prefsUI" style="width: 100%;"> <tr id="copyRegexPrefsStyleRow" class="copyRegexPrefsRow"> <td class="UIlabel">Copied Regex Escape Style:</td> <td colspan="2" class="UIcontrol" style="width: 58%;"> <select id="copyRegexPrefsStyle" class="copyRegexPrefsControl"> <option>None</option> <option>Escape Only</option> <option>C String</option> <option>NSString</option> </select> </td> </tr> <tr id="copyRegexPrefsSmartEscapeRow" class="copyRegexPrefsRow"> <td class="UIlabel">Escape Style Options:</td> <td class="UIcontrol"><input type=checkbox id="copyRegexPrefsSmartEscape" class="copyRegexPrefsControl"></td> <td class="UIcontrolLabel"><span>Smart escape</span></td> </tr> <tr id="copyRegexPrefsUseC99Row" class="copyRegexPrefsRow"> <td class="UIlabel">&nbsp;</td> <td class="UIcontrol"><input type=checkbox id="copyRegexPrefsUseC99" class="copyRegexPrefsControl"></td> <td class="UIcontrolLabel"><span>Use <b>C99</b> <span class="code">\u</span> character escapes</span></td> </tr> <tr id="copyRegexPrefsUnicodeInNSStringsRow" class="copyRegexPrefsRow"> <td class="UIlabel">&nbsp;</td> <td class="UIcontrol"><input type=checkbox id="copyRegexPrefsUnicodeInNSStrings" class="copyRegexPrefsControl"></td> <td class="UIcontrolLabel"><span>Escaped Unicode in <span class="code">NSString</span> literals</span></td> </tr> </table> <div class="prefWarnings" id="prefWarnings"> <hr class="beveled"> <div class="prefWarningsSpacer" id="prefWarningsSpacer"> <div class="table prefWarningsTable copyRegexPrefsWarning" id="smartEscapeWarning"> <div class="row prefWarning"> <div class="cell label"><b>Note:</b></div> <div class="cell message">The escaped regular expression may be slightly different than the original because some escape sequences are parsed and rewritten.</div> </div> </div> <div class="table prefWarningsTable copyRegexPrefsWarning" id="c99Warning"> <div class="row prefWarning"> <div class="cell label"><b>Note:</b></div> <div class="cell message">Use of <span class="quotedText">\u</span> character escapes requires the <b>C99</b> standard with the execution character set set to <span class="quotedText">UTF-8</span> (the default for <span class="quotedText">gcc</span>).</div> </div> </div> <div class="table prefWarningsTable copyRegexPrefsWarning" id="nsstringUnicodeWarning"> <div class="row prefWarning"> <div class="cell label"><b>Note:</b></div> <div class="cell message">Escaped Unicode in <span class="code">NSString</span> literals requires <span class="hardNobr">Xcode &ge; 3.0</span> and <span class="hardNobr"><span class="quotedText">gcc</span> &ge; 4.0.</span></div> </div> </div> </div> </div> </div></div></div> <div class="clipboardExamples" id="topContainer"> <p class="UIlabel">Escape Style Preview:</p> <div id="shadow"> <div id="clip"> <script type="text/javascript"> var exampleRegexArray = ["(\\d+)", "[\\$|\u20AC]", "\"Yes\\?\\n\"", "\"([^\\\"]*)\"", "(?:SS|\u00df)"]; //" document.writeln(buildPreviewTables("cbe_bg", "style='margin: 0px;'", exampleRegexArray)); document.writeln(buildPreviewTables("cbe_a", "style='margin: 0px; display: block;'", exampleRegexArray).replace(/class="([^"]*)"/, "class=\"$1 active\"")); document.writeln(buildPreviewTables("cbe_b", "style='margin: 0px; display: block;'", exampleRegexArray).replace(/class="([^"]*)"/, "class=\"$1 inactive\"")); </script> </div> </div> </div> </div> </div> </div> <div class="box titled screenOnly regexEscapeTool UIpane clearBoth noSelect" id="RegexEscapeTool"> <div class="title blueGrey">Regex Escape Tool</div> <div class="contents alum2"> <div class="UIcontentSpacer"> <div class="contain"> <textarea cols="30" rows="3" class="UIcontrol regex canSelect" id="interactiveEscapedInput">Number: \d+</textarea> </div> <div style="margin-top: 0.25em;"> <p class="UIlabel noSelect" style="margin-bottom: 0.25em; margin-left: 0.5ex;">Preview:</p> <div class="insetOuter"><div class="insetMiddle"><div class="inset"> <div class="UImessage regex doNotEscape canSelect" id="interactiveEscapedOutput">&nbsp;</div> </div></div></div> </div> </div> </div> </div> <p>This browser supports Copy To Clipboard features that can be used by this document. Using the <a href="#copyRegexToClipboardPreferences">Copy Regex to Clipboard Preferences</a> interface, you can configure the behavior of <span class="context-menu">Edit </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Copy</span> so that when you select and copy a regular expression in this document, the clipboard will contain the selected regular expression that has been escaped according to your preference choices. The resulting text in the clipboard can be pasted directly in to your source code, no further modification of the regular expression is required.</p> <p>Your preference choices are stored in the browser using a cookie. Provided that cookies are enabled in your browser, your preferences should persist across browser sessions. The preference panel also contains a preview of what would be copied to the clipboard for some example regular expressions using the current settings. When you change a setting in the preferences, the examples will transition between the previous settings and the new settings, while briefly highlighting the differences between the two settings, so you can determine the effect the change has caused.</p> <p>Some of the problems of using regular expressions unmodified in <b>C</b> and <b class="hardNobr">Objective-C</b> are:</p> <ul class="square"> <li>String literals in <b>C</b> use the <span class="consoleText" title="Backslash">\</span> character as the escape character. Regular expressions typically make heavy use of the <span class="consoleText" title="Backslash">\</span> character and each use of the character must be escaped, resulting in <span class="consoleText" title="Backslash Backslash">\\</span>.</li> <li>The use of the <span class="consoleText" title="Quote">&quot;</span> quote character must be escaped, resulting in <span class="consoleText" title="Backslash Quote">\&quot;</span></li> <li>Unicode characters must be escaped in a compatible way.</li> </ul> <p>There are several different ways to escape Unicode characters. When using Unicode characters in <span class="code">NSString</span> literals, the best method depends on the version of Xcode that is used to compile the source and what <b>C</b> standard you are using <span class="hardNobr">(i.e., <span class="consoleText">gcc -std=</span><span class="parameterChoice">(c|gnu)</span><span class="consoleText">99</span>)</span>.</p> <p>When the <span class="context-menu">Copied Regex Escape Style</span> is set to <span class="dialog-option">None</span>, then the selected regular expression is copied unmodified to the clipboard.</p> <p>When the <span class="context-menu">Copied Regex Escape Style</span> is set to <span class="dialog-option">Escape Only</span>, <span class="dialog-option">C String</span>, or <span class="dialog-option">NSString</span> then these details are automatically dealt with for you. This allows you to paste the selected regular expression directly in to your source code without having to escape every use of <span class="consoleText" title="Backslash">\</span> by hand, or having to convert the Unicode characters in to a acceptable format.</p> <h4>Escape Option Details</h4> <h5>Smart escape</h5> <p>If this option is <i><b>disabled</b></i> then all occurrences of <span class="consoleText" title="Backslash">\</span> and <span class="consoleText" title="Quote">&quot;</span> are escaped with a <span class="consoleText" title="Backslash">\</span>, resulting in <span class="consoleText" title="Backslash Backslash">\\</span> or <span class="consoleText" title="Backslash Quote">\&quot;</span>. No other processing is performed. Since this prevents the <b>C</b> compiler from interpreting any special meaning of <span class="consoleText" title="Backslash">\</span> sequences, it is the safest option. The ICU regular expression engine is then responsible for interpreting the meaning of any <span class="hardNobr"><span class="consoleText" title="Backslash">\</span> escaped</span> character sequences.</p> <p>If this option is <i><b>enabled</b></i> then certain escape sequences are interpreted and rewritten using the current preference options.</p> <h5>Use <b>C99</b> <span class="consoleText">\u</span> character escapes</h5> <p>Normally, Unicode characters are embedded in string literals as the characters <span class="code hardNobr">UTF-8</span> byte sequence using <span class="hardNobr"><span class="consoleText">\</span><i>ddd</i></span> octal escapes. When this option is enabled, the <b>C99</b> <span class="consoleText">\u</span> and <span class="consoleText">\U</span> character escape sequences are used instead. <span class="consoleText">gcc</span> will issue a warning if <span class="consoleText">\u</span> character escape sequences are present and the compiler is not configured to use the <b>C99</b> (or later) standard <span class="hardNobr">(i.e., <span class="consoleText">gcc -std=</span><span class="parameterChoice">(c|gnu)</span><span class="consoleText">99</span>).</span></p> <p>Under the <b>C99</b> standard, <span class="consoleText">\u</span> and <span class="consoleText">\U</span> are used to specify a <i>universal character name</i>, which is a character encoded in the <span class="hardNobr">ISO/IEC 10646</span> character set (essentially identical to Unicode in this context). Ultimately, a <i>universal character name</i> is translated in to a sequence of bytes needed to represent the designated character in the <b>C</b> environments <i>execution character set</i>. Usually, although certainly not always, a string literal should be encoded as <span class="code hardNobr">UTF-8</span>, which happens to be the default <i>execution character set</i> for <span class="consoleText">gcc</span>. This is an important point to remember because the more convenient and easier to use <span class="consoleText">\u</span> escape sequences are not guaranteed to convert in to a specific sequence of bytes, unlike an <span class="hardNobr">octal <span class="consoleText">\</span><i>ddd</i></span> or <span class="hardNobr">hex <span class="consoleText">\x</span><i>hh</i></span> escape sequence. There is currently no way to specify that a particular string literal should always be translated using a specific character set encoding. This may result in undefined behavior if the <span class="consoleText">\u</span> universal character name is not translated in to the expected character set, which in this case must be <span class="code hardNobr">UTF-8</span>.</p> <h5>Escaped Unicode in <span class="code">NSString</span> literals</h5> <p>Prior to Xcode 3.0, <span class="consoleText">gcc</span> only supported the use of <span class="code">ASCII</span> characters <span class="hardNobr">(i.e., characters &le; 127)</span> in constant <span class="code">NSString</span> literals. If one needed to include Unicode characters in an <span class="code">NSString</span>, one would typically convert the string in to <span class="code hardNobr">UTF-8</span>, and then create a <span class="code">NSString</span> at run time using the <span class="code">stringWithUTF8String:</span> method, with the <span class="code hardNobr">UTF-8</span> encoded <b>C</b> string passed as the argument. For example, <span class="hardNobr">&quot;<span class="code">&euro;1.99</span>&quot;</span>, which contains the &euro; euro symbol, would be created using the following:</p> <div class="box sourcecode">NSString *euroString = [NSString stringWithUTF8String:"\342\202\2541.99"]; // <span class="comment">or with C99 \u character escapes:</span> NSString *euroString = [NSString stringWithUTF8String:"\u20ac1.99"];</div> <p>One of the obvious disadvantages of this approach is that it instantiates a new, autoreleased <span class="code">NSString</span> each time it&#39;s used, unlike a constant <span class="code">NSString</span> literal like <span class="code">@&quot;$1.99&quot;</span>. Beginning with Xcode 3.0 and gcc 4.0, constant <span class="code">NSString</span> literals that contain Unicode characters can be specified directly in source-code using the standard <span class="code">@&quot;&quot;</span> syntax. For example:</p> <div class="box sourcecode">NSString *euroString = @"\342\202\2541.99"; // <span class="comment">or with C99 \u character escapes:</span> NSString *euroString = @"\u20ac1.99";</div> <p>The compiler converts these strings to <span class="code hardNobr">UTF-16</span> using the endianness of the target architecture. Since <span class="hardNobr">Mach-O</span> object file format allows for multiple architectures, this allows each architecture to encode the string as native <span class="code hardNobr">UTF-16</span> byte ordering for that architecture, so there are no issues with proper byte ordering. Within the object file itself, these strings are essentially identical to their <span class="hardNobr"><span class="code">ASCII</span>-only</span> counterparts: effectively they are pre-instantiated objects. The only real difference is that the compiler sets some internal <span class="code">CFString</span> bits differently so that the <span class="code">CFString</span> object knows that the strings data is encoded as <span class="code hardNobr">UTF-16</span> and not simple <span class="hardNobr">8-bit</span> data.</p> <p>Although this functionality has been present since the release of 10.5, it has only recently been documented in <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocLanguageSummary.html#//apple_ref/doc/uid/TP30001163-CH3-TPXREF104" class="printURL section-link">The Objective-C 2.0 Programming Language - Compiler Directives</a>, under the <span class="hardNobr code">@&quot;string&quot;</span> entry. A copy of the relevant text is provided below:</p> <div class="box quote"><p>On <span class="hardNobr">Mac OS X v10.4</span> and earlier, the string must be <span class="hardNobr code">7-bit</span> <span class="hardNobr"><span class="hardNobr code">ASCII</span>-encoded.</span> On <span class="hardNobr">Mac OS X v10.5</span> and later (with <span class="hardNobr">Xcode 3.0</span> and later), you can also use <span class="hardNobr code">UTF-16</span> encoded strings. (The runtime from <span class="hardNobr">Mac OS X v10.2</span> and later supports <span class="hardNobr code">UTF-16</span> encoded strings, so if you use <span class="hardNobr">Mac OS X v10.5</span> to compile an application for <span class="hardNobr">Mac OS X v10.2</span> and later, you can use <span class="hardNobr code">UTF-16</span> encoded strings.)</p></div> <h4>Visual Indication that the Selected Text has been Escaped</h4> <p>This document will briefly add a red outline around the selected text as a visual aid in determining whether or not the selected text was modified before placing it in the clipboard. In addition to this, a <span title="Heads Up Display">HUD</span> display will drop down briefly at the top of the documents window and will display the escaped text that was placed in to the clipboard. Here is an example of what would be displayed if the <span class="context-menu">NSString</span> escape style was selected:</p> <div class="table copyToClipboardDisplayExample"><div class="row"> <div class="cell">The outline that is display when a regular expression is selected and copied to the clipboard: <span class="pulseOutlineRed" style="background: highlight; background: -moz-mac-accentregularhighlight; margin-left: 1ex; margin-right: 1.5ex; "><span class="regex">(\d+):\s*(.*)</span></span></div> <div class="cell">The drop down HUD that would be displayed:</div> <div class="cell"> <div class="screenOnly copyToClipboardHUD example"> <div class="top"> <div class="padding"> <div class="copiedAs">Copied to Clipboard as:</div> <div class="regex copyToClipboardHUDRegex">@&quot;(\\d+):\\s*(.*)&quot;</div> </div> </div> </div> </div> </div></div> <p>The selected text will only be escaped if it can be determined that it is a regular expression, and the selection only contains a regular expression. If the regular expression is part of an overall larger selection then the text that is copied to the clipboard is not modified.</p> <div class="box note clearBoth"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>The method used to escape regular expressions is only a simple set of heuristics. While these heuristics seem to work correctly for a variety of inputs, it is by no means error-free. You should always double check the escaped output for errors.</p> </div></div></div></div> <h4>Regex Escape Tool</h4> <p>Also available is the <a href="#RegexEscapeTool">Regex Escape Tool</a> which allows you to enter a regular expression and have it immediately escaped using the current preference settings. This can be useful if you have a complex regular expression that needs to be escaped before you can use it in a constant <span class="code">NSString</span> literal. It can also be used to easily create a constant <span class="code">NSString</span> literal that contains several Unicode characters that would otherwise have to be manually converted by hand.</p> </div> <!-- enhancedCopyOnly screenOnly --> <h3 style="clear: Both" id="RegexKitLiteCookbook_PatternMatchingRecipes">Pattern Matching Recipes</h3> <h4 id="RegexKitLiteCookbook_PatternMatchingRecipes_Numbers">Numbers</h4> <table class="slate regexList"> <tr><th>Description</th><th>Regex</th><th>Examples</th></tr> <tr><td class="description">Integer</td><td class="regex">[+\-]?[0-9]+</td><td class="example"><span class="regexMatch">123</span><span class="regexMatch">-42</span><span class="regexMatch">+23</span></td></tr> <tr><td class="description">Hex Number</td><td class="regex">0[xX][0-9a-fA-F]+</td><td class="example"><span class="regexMatch">0x0</span><span class="regexMatch">0xdeadbeef</span><span class="regexMatch">0xF3</span></td></tr> <tr><td class="description">Floating Point</td><td class="regex">[+\-]?(?:[0-9]*\.[0-9]+|[0-9]+\.)</td><td class="example"><span class="regexMatch">123.</span><span class="regexMatch">.123</span><span class="regexMatch">+.42</span></td></tr> <tr><td class="description">Floating Point with Exponent</td><td class="regex">[+\-]?(?:[0-9]*\.[0-9]+|[0-9]+\.)(?:[eE][+\-]?[0-9]+)?</td><td class="example"><span class="regexMatch">123.</span><span class="regexMatch">.123</span><span class="regexMatch">10.0E13</span><span class="regexMatch">1.23e-7</span></td></tr> <tr><td class="description">Comma Separated Number</td><td class="regex">[0-9]{1,3}(?:,[0-9]{3})*</td><td class="example"><span class="regexMatch">42</span><span class="regexMatch">1,234</span><span class="regexMatch">1,234,567</span></td></tr> <tr><td class="description">Comma Separated Number</td><td class="regex">[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?</td><td class="example"><span class="regexMatch">42</span><span class="regexMatch">1,234</span><span class="regexMatch">1,234,567.89</span></td></tr> </table> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_Numbers_ExtractingandConvertingNumbers">Extracting and Converting Numbers</h5> <p><span class="code">NSString</span> includes several methods for converting the contents of the string in to a numeric value in the various <b>C</b> primitive types. The following demonstrates the matching of an <span class="code">int</span> and <span class="code">double</span> in a <span class="code">NSString</span>, and then converting the matched string in to its base type.</p> <div class="box sourcecode clearBoth"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Integer conversion&hellip;</span></span></div>NSString *searchString = @&quot;The int 5542 to convert&quot;; NSString *regexString = @&quot;([+\\-]?[0-9]+)&quot;; int matchedInt = [[searchString <span class="hardNobr">stringByMatching:regexString</span> <span class="hardNobr">capture:1L]</span> <span class="hardNobr">intValue];</span></div> <p>The variable <span class="code">matchedInt</span> now contains the value of <span class="code">5542</span>.</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Floating Point conversion&hellip;</span></span></div>NSString *searchString = @&quot;The double 4321.9876 to convert&quot;; NSString *regexString = <span class="hardNobr">@&quot;([+\\-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.))&quot;;</span> double matchedDouble = [[searchString <span class="hardNobr">stringByMatching:regexString</span> <span class="hardNobr">capture:1L]</span> <span class="hardNobr">doubleValue];</span></div> <p>The variable <span class="code">matchedDouble</span> now contains the value of <span class="code">4321.9876</span>. <span class="code">doubleValue</span> can even convert numbers that are in scientific notation, which represent numbers <span class="hardNobr">as <i>n</i> &times; 10<sup><i>exp</i></sup>:</span></p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Floating Point conversion&hellip;</span></span></div>NSString *searchString = @&quot;The double 1.010489e5 to convert&quot;; NSString *regexString = <span class="hardNobr">@&quot;([+\\-]?(?:[0-9]*\\.[0-9]+|[0-9]+\\.)(?:[eE][+\\-]?[0-9]+)?)&quot;;</span> double matchedDouble = [[searchString <span class="hardNobr">stringByMatching:regexString capture:1L]</span> <span class="hardNobr">doubleValue];</span></div> <p>The variable <span class="code">matchedDouble</span> now contains the value of <span class="code">101048.9</span>.</p> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_Numbers_ExtractingandConvertingHexNumbers">Extracting and Converting Hex Numbers</h5> <p>Converting a string that contains a hex number in to a more basic type, such as an <span class="code">int</span>, takes a little more work. Unfortunately, Foundation does not provide an easy way to convert a hex value in a string in to a more basic type as it does with <span class="code">intValue</span> or <span class="code">doubleValue</span>. Thankfully the standard <b>C</b> library provides a set of functions for performing such a conversion. For this example we will use the <span class="code">strtol()</span> (<i>string to long</i>) function to convert the hex value we&#39;ve extracted from <span class="code">searchString</span>. We can not pass the pointer to the <span class="code">NSString</span> object that contains the matched hex value since <span class="code">strtol()</span> is part of the standard <b>C</b> library which can only work on pointers to <b>C</b> strings. We use the <span class="code">UTF8String</span> method to get a pointer to a compatible <b>C</b> string of the matched hex value.</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Hex conversion&hellip;</span></span></div>NSString *searchString = @&quot;A hex value: 0x0badf00d&quot;; NSString *regexString = @&quot;\\b(0[xX][0-9a-fA-F]+)\\b&quot;; NSString *hexString = [searchString stringByMatching:regexString <span class="hardNobr">capture:1L];</span> // <span class="comment">Use strtol() to convert the string to a long.</span> long hexLong = strtol([hexString UTF8String], NULL, 16); NSLog(@&quot;hexLong: 0x%lx / %ld&quot;, (u_long)hexLong, hexLong); // <span class="comment">2008-09-01 09:40:44.848 hex_example[30583:807] hexLong: 0xbadf00d / 195948557</span></div> <p>The full set of <i>string to&hellip;</i> functions are: <span class="code">strtol()</span>, <span class="code">strtoll()</span>, <span class="code">strtoul()</span>, and <span class="code">strtoull()</span>. These convert a string value, from base 2 to base 36, in to a <span class="code">long</span>, <span class="code">long long</span>, <span class="code">unsigned long</span>, and <span class="code">unsigned long long</span> respectively.</p> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_Numbers_AddingHexValueConversionstoNSString">Adding Hex Value Conversions to <span class="code">NSString</span></h5> <p>Since it seems to be a frequently asked question, and a common search engine query for RegexKit web site visitors, here is a <span class="code">NSString</span> category addition that converts the receivers text in to a <span class="code">NSInteger</span> value. This is the same functionality as <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue" class="code">intValue</a> or <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/doubleValue" class="code">doubleValue</a>, except that it converts hexadecimal text values instead of decimal text values.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>The following code can also be found in the <span class="rkl">RegexKit<i>Lite</i></span> distributions <span class="file">examples/</span> directory.</p> </div></div></div></div> <p>The example conversion code is fairly quick since it uses <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> directly along with the stack to hold any temporary string conversions. Any whitespace at the beginning of the string will be skipped and the hexadecimal text to be converted may be optionally prefixed with either <span class="consoleText">0x</span> or <span class="consoleText">0X</span>. Returns <span class="code">0</span> if the receiver does not begin with a valid hexadecimal text representation. Refer to <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/strtol.3.html" class="code">strtol(3)</a> for additional conversion details.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>If the receiver needs to be converted in to an encoding that is compatible with <span class="code">strtol()</span>, only the first sixty characters of the receiver are converted.</p> </div></div></div></div> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">NSString-HexConversion.h</span></span></div>#import &lt;Foundation/NSString.h&gt; @interface NSString (HexConversion) -(NSInteger)hexValue; @end</div> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">NSString-HexConversion.m</span></span></div>#import &quot;NSString-HexConversion.h&quot; #import &lt;CoreFoundation/CFString.h&gt; #include &lt;stdlib.h&gt; @implementation NSString (HexConversion) -(NSInteger)hexValue { CFStringRef cfSelf = (CFStringRef)self; UInt8 buffer[64]; const char *cptr; if((cptr = CFStringGetCStringPtr(cfSelf, kCFStringEncodingMacRoman)) == NULL) { CFRange range = CFRangeMake(0L, CFStringGetLength(cfSelf)); CFIndex usedBytes = 0L; CFStringGetBytes(cfSelf, range, kCFStringEncodingUTF8, &#39;?&#39;, false, buffer, 60L, &amp;usedBytes); buffer[usedBytes] = 0; cptr = (const char *)buffer; } return((NSInteger)strtol(cptr, NULL, 16)); } @end</div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/strtol.3.html" class="code">strtol(3)</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue" class="code">- intValue</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/doubleValue" class="code">- doubleValue</a></li> </ul> </div> <h4 id="RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles">Text Files</h4> <table class="slate regexList"> <tr><th>Description</th><th>Regex</th></tr> <tr><td class="description">Empty Line</td><td class="regex">(?m:^$)</td></tr> <tr><td class="description">Empty or Whitespace Only Line</td><td class="regex">(?m-s:^\s*$)</td></tr> <tr><td class="description">Strip Leading Whitespace</td><td class="regex">(?m-s:^\s*(.*?)$)</td></tr> <tr><td class="description">Strip Trailing Whitespace</td><td class="regex">(?m-s:^(.*?)\s*$)</td></tr> <tr><td class="description">Strip Leading and Trailing Whitespace</td><td class="regex">(?m-s:^\s*(.*?)\s*$)</td></tr> <tr><td class="description">Quoted String, Can Span Multiple Lines, May Contain \&quot;</td><td class="regex">&quot;(?:[^&quot;\\]*+|\\.)*&quot;</td></tr> <tr><td class="description">Quoted String, Single Line Only, May Contain \&quot;</td><td class="regex">&quot;(?:[^&quot;\\\r\n]*+|\\[^\r\n])*&quot;</td></tr> <tr><td class="description">HTML Comment</td><td class="regex">(?s:&lt;&#45;&#45;.*?&#45;&#45;&gt;)</td></tr> <tr><td class="description">Perl / Shell Comment</td><td class="regex">(?m-s:#.*$)</td></tr> <tr><td class="description">C, C++, or ObjC Comment</td><td class="regex">(?m-s://.*$)</td></tr> <tr><td class="description">C, C++, or ObjC Comment and Leading Whitespace</td><td class="regex">(?m-s:\s*//.*$)</td></tr> <tr><td class="description">C, C++, or ObjC Comment</td><td class="regex">(?s:/\*.*?\*/)</td></tr> </table> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles_TheNewlineDebacle">The Newline Debacle</h5> <p>Unfortunately, when processing text files, there is no standard &#39;newline&#39; character or character sequence. Today this most commonly surfaces when converting text between Microsoft Windows / MS-DOS and Unix / <span class="hardNobr">Mac OS X</span>. The reason for the proliferation of newline standards is largely historical and goes back many decades. Below is a table of the dominant newline character sequence &#39;standards&#39;:</p> <table class="slate charactersList"> <tr><th>Description</th><th>Sequence</th><th>C String</th><th>Control</th><th>Common Uses</th></tr> <tr><td>Line Feed</td><td class="characters">\u000A</td><td class="consoleText">\n</td><td class="consoleText">^J</td><td>Unix, Amiga, Mac OS X</td></tr> <tr><td>Vertical Tab</td><td class="characters">\u000B</td><td class="consoleText">\v</td><td class="consoleText">^K</td><td>&nbsp;</td></tr> <tr><td>Form Feed</td><td class="characters">\u000C</td><td class="consoleText">\f</td><td class="consoleText">^L</td><td>&nbsp;</td></tr> <tr><td>Carriage Return</td><td class="characters">\u000D</td><td class="consoleText">\r</td><td class="consoleText">^M</td><td>Apple ][, Mac OS &le; 9</td></tr> <tr><td>Next Line (NEL)</td><td class="characters">\u0085</td><td class="consoleText">&nbsp;</td><td class="consoleText"></td><td>IBM / EBCDIC</td></tr> <tr><td>Line Separator</td><td class="characters">\u2028</td><td class="consoleText">&nbsp;</td><td class="consoleText"></td><td>Unicode</td></tr> <tr><td>Paragraph Separator</td><td class="characters">\u2029</td><td class="consoleText">&nbsp;</td><td class="consoleText"></td><td>Unicode</td></tr> <tr><td>Carriage Return + Line Feed</td><td class="characters">\u000D\u000A</td><td class="consoleText">\r\n</td><td class="consoleText">^M^J</td><td>MS-DOS, Windows</td></tr> </table> <p>Ideally, one should be flexible enough to accept any of these character sequences if one has to process text files, especially if the origin of those text files is not known. Thankfully, regular expressions excel at just such a task. Below is a regular expression pattern that will match any of the above character sequences. This is also the character sequence that the metacharacter <span class="regex">$</span> matches.</p> <table class="slate regexList"> <tr><th>Description</th><th>Regex</th><th>Notes</th></tr> <tr><td class="description">Any newline</td><td class="regex">(?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}])</td><td class="note">UTS #18 recommended. Character sequence that <span class="regex">$</span> matches.</td></tr> </table> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://www.unicode.org/reports/tr18/#Line_Boundaries" class="section-link printURL">UTS #18: Unicode Regular Expressions - Line Boundaries</a></li> <li><a href="http://en.wikipedia.org/wiki/Newline" class="section-link printURL">Wikipedia - Newline</a></li> </ul> </div> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles_MatchingtheBeginningandEndofaLine">Matching the Beginning and End of a Line</h5> <p>It is often necessary to work with the individual lines of a file. There are two regular expression metacharacters, <span class="regex">^</span> and <span class="regex">$</span>, that match the <i>beginning</i> and <i>end</i> of a line, respectively. However, exactly what is matched by <span class="regex">^</span> and <span class="regex">$</span> depends on whether or not the <span class="regex-def">multi-line</span> option is enabled for the regular expression, which by default is disabled. It can be enabled for the entire regular expression by passing <a href="#RKLRegexOptions_RKLMultiline" class="code">RKLMultiline</a> via the <span class="code">options:</span> method argument, or within the regular expression using the options syntax&mdash; <span class="regex">(?m:</span>&hellip;<span class="regex">)</span>.</p> <p>If <span class="regex-def">multi-line</span> is <b><i>disabled</i></b>, then <span class="regex">^</span> and <span class="regex">$</span> match the beginning and end of the entire string. If there is a <span class="regex-def">newline</span> character sequence at the very end of the string, then <span class="regex">$</span> will match the character just before the <span class="regex-def">newline</span> character sequence. Any <span class="regex-def">newline</span> character sequences in the middle of the string will <b><i>not</i></b> be matched.</p> <p>If <span class="regex-def">multi-line</span> is <b><i>enabled</i></b>, then <span class="regex">^</span> and <span class="regex">$</span> match the beginning and end of a line, where the end of a line is the <span class="regex-def">newline</span> character sequence. The metacharacter <span class="regex">^</span> matches either the first character in the string, or the first character following a <span class="regex-def">newline</span> character sequence. The metacharacter <span class="regex">$</span> matches either the last character in the string, or the character just before a <span class="regex-def">newline</span> character sequence.</p> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles_CreatingaNSArrayContainingEveryLineinaString">Creating a <span class="code">NSArray</span> Containing Every Line in a String</h5> <p>A common text processing pattern is to process a file one line at a time. Using the recommended regular expression for matching any newline and the <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">componentsSeparatedByRegex:</a> method, you can easily create a <span class="code">NSArray</span> containing every line in a file and process it one line at a time:</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Process every line&hellip;</span></span></div>NSString *fileNameString = @&quot;example&quot;; NSString *regexString = <span class="hardNobr">@&quot;(?:\r\n|[\n\v\f\r\302\205\\p{Zl}\\p{Zp}])&quot;;</span> NSError *error = NULL; NSString *fileString = [NSString <span class="hardNobr">stringWithContentsOfFile:fileNameString</span> <span class="hardNobr">usedEncoding:NULL</span> <span class="hardNobr">error:&amp;error];</span> if(fileString) { NSArray *linesArray = [fileString <span class="hardNobr">componentsSeparatedByRegex:regexString];</span> for(NSString *lineString in linesArray) { <span class="hardNobr">// <span class="comment">ObjC 2.0 for&hellip;in loop.</span></span> // <span class="comment">Per line processing.</span> } } else { NSLog(@&quot;Error reading file &#39;%@&#39;&quot;, fileNameString); if(error) { NSLog(@&quot;Error: %@&quot;, error); } }</div> <p>The <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">componentsSeparatedByRegex:</a> method effectively &#39;chops off&#39; the matched regular expression, or in this case any newline character. In the example above, within the <span class="code">for&hellip;in</span> loop, <span class="code">lineString</span> will not have a newline character at the end of the string.</p> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_TextFiles_ParsingCSVData">Parsing CSV Data</h5> <table class="slate regexList"> <tr><th>Description</th><th>Regex</th></tr> <tr><td class="description">Split CSV line</td><td class="regex"> <span class="softNobr"> <span class="tbrOn">,(?=(?:(?:[^&quot;\\]*+|\\&quot;)*&quot;(?:[^&quot;\\]*+|\\&quot;)*&quot;)&#8203;*(?!(?:[^&quot;\\]*+|\\&quot;)*&quot;(?:[^&quot;\\]*+|\\&quot;)*$))</span> <span class="tbrOff">,(?=(?:(?:[^&quot;\\]*+|\\&quot;)*&quot;(?:[^&quot;\\]*+|\\&quot;)*&quot;)*(?!(?:[^&quot;\\]*+|\\&quot;)*&quot;(?:[^&quot;\\]*+|\\&quot;)*$))</span> </span> </td></tr> </table> <p>This regular expression essentially works by ensuring that there are an even number of unescaped <span class="regex">&quot;</span> quotes following a <span class="regex">,</span> comma. This is done by using <i>look-head assertions</i>. The first <i>look-head assertion</i>, <span class="regex">(?=</span>, is a pattern that matches zero or more strings that contain two <span class="regex">&quot;</span> characters. Then, a <i>negative look-head assertion</i> matches a single, unpaired <span class="regex">&quot;</span> quote character remaining at the <span class="regex">$</span> end of the line. It also uses <i>possessive matches</i> in the form of <span class="regex">*+</span> for speed, which prevents the regular expression engine from backtracking excessively. It&#39;s certainly not a beginners regular expression.</p> <p>The following is used as a substitute for a CSV data file in the example below.</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Example CSV data&hellip;</span></span></div><span class="printOnly"><br></span>NSString *csvFileString <span class="softNobr">= @&quot;RegexKitLite,1.0,\&quot;Mar 23, 2008\&quot;,27004\n&quot;</span> <span class="softNobr">@&quot;RegexKitLite,1.1,\&quot;Mar 28, 2008\&quot;,28081\n&quot;</span> <span class="softNobr">@&quot;RegexKitLite,1.2,\&quot;Apr 01, 2008\&quot;,28765\n&quot;</span> <span class="softNobr">@&quot;RegexKitLite,2.0,\&quot;Jul 07, 2008\&quot;,40569\n&quot;</span> <span class="softNobr">@&quot;RegexKitLite,2.1,\&quot;Jul 12, 2008\&quot;,40660\n&quot;;</span></div> <p>This example really highlights the power of regular expressions when it comes to processing text. It takes just 17 lines, which includes comments, to parse a CSV data file of any newline type and create a <i>row</i> by <i>column</i> of <span class="code">NSArray</span> values of the results while correctly handling <span class="regex">&quot;</span> quoted values, including escaped <span class="regex">\&quot;</span> quotes.</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">Parse CSV data&hellip;</span></span></div><span class="printOnly"><br></span>NSString *newlineRegex <span class="hardNobr">= @&quot;(?:\r\n|[\n\v\f\r\\x85\\p{Zl}\\p{Zp}])&quot;;</span> NSString *splitCSVLineRegex <span class="softNobr">= @&quot;<span class="softNobr"><span class="tbrOn">,(?=(?:(?:[^\&quot;\\\\]*+|\\\\\&quot;)*&#8203;\&quot;(?:[^\&quot;\\\\]*+|\\\\\&quot;)*\&quot;)*&#8203;(?!(?:[^\&quot;\\\\]*+|\\\\\&quot;)*&#8203;\&quot;(?:[^\&quot;\\\\]*+|\\\\\&quot;)*$))</span><span class="tbrOff">,(?=(?:(?:[^\&quot;\\\\]*+|\\\\\&quot;)*\&quot;(?:[^\&quot;\\\\]*+|\\\\\&quot;)*\&quot;)*(?!(?:[^\&quot;\\\\]*+|\\\\\&quot;)*\&quot;(?:[^\&quot;\\\\]*+|\\\\\&quot;)*$))</span></span>&quot;;</span> // <span class="comment">Create a NSArray of every line in csvFileString.</span> NSArray *csvLinesArray = <span class="hardNobr">[csvFileString componentsSeparatedByRegex:</span><span class="hardNobr">newlineRegex];</span> // <span class="comment">Create an id array to hold the comma split line results.</span> id splitLines[[csvLinesArray count]]; // <span class="comment">C99 variable length array.</span> NSUInteger splitLinesIndex = 0UL; <span class="screenOnly">&nbsp; </span>// <span class="comment">Index of next splitLines[] member.</span> for(NSString *csvLineString in csvLinesArray) { <span class="screenOnly">&nbsp; </span>// <span class="comment">ObjC 2 for&hellip;in loop.</span> if([csvLineString <span class="hardNobr">isMatchedByRegex:@&quot;^\\s*$&quot;])</span> <span class="hardNobr">{ continue; }</span> // <span class="comment">Skip empty lines.</span> splitLines[splitLinesIndex++] = [csvLineString <span class="hardNobr">componentsSeparatedByRegex:</span><span class="hardNobr">splitCSVLineRegex];</span> } // <span class="comment">Gather up all the individual comma split results in to a single NSArray.</span> NSArray *splitLinesArray = [NSArray <span class="hardNobr">arrayWithObjects:</span><span class="hardNobr">&amp;splitLines[0]</span> <span class="hardNobr">count:</span><span class="hardNobr">splitLinesIndex];</span></div> <h4 id="RegexKitLiteCookbook_PatternMatchingRecipes_NetworkandURL">Network and URL</h4> <table class="slate regexList"> <tr><th>Description</th><th>Regex</th></tr> <tr><td class="description">HTTP</td><td class="regex">\bhttps?://[a-zA-Z0-9\-.]+(?:(?:/[a-zA-Z0-9\-._?,&#39;+\&amp;%$=~*!():@\\]*)+)?</td></tr> <tr><td class="description">HTTP</td><td class="regex">\b(https?)://([a-zA-Z0-9\-.]+)((?:/[a-zA-Z0-9\-._?,&#39;+\&amp;%$=~*!():@\\]*)+)?</td></tr> <tr><td class="description">HTTP</td><td class="regex">\b(https?)://(?:(\S+?)(?::(\S+?))?@)?([a-zA-Z0-9\-.]+)(?::(\d+))?((?:/[a-zA-Z0-9\-._?,&#39;+\&amp;%$=~*!():@\\]*)+)?</td></tr> <tr><td class="description">E-Mail</td><td class="regex">\b([a-zA-Z0-9%_.+\-]+)@([a-zA-Z0-9.\-]+?\.[a-zA-Z]{2,6})\b</td></tr> <tr><td class="description">Hostname</td><td class="regex">\b(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}?[a-zA-Z0-9]\.)+[a-zA-Z]{2,6}\b</td></tr> <tr><td class="description">IP</td><td class="regex">\b(?:\d{1,3}\.){3}\d{1,3}\b</td></tr> <tr><td class="description">IP with Optional Netmask</td><td class="regex">\b((?:\d{1,3}\.){3}\d{1,3})(?:/(\d{1,2}))?\b</td></tr> <tr><td class="description">IP or Hostname</td><td class="regex">\b(?:(?:\d{1,3}\.){3}\d{1,3}|(?:[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}?[a-zA-Z0-9]\.)+[a-zA-Z]{2,6})\b</td></tr> </table> <h5 id="RegexKitLiteCookbook_PatternMatchingRecipes_NetworkandURL_CreatingaNSDictionaryofURLInformation">Creating a <span class="code">NSDictionary</span> of URL Information</h5> <p>The following example demonstrates how to match several fields in a URL and create a <span class="code">NSDictionary</span> with the extracted results. Only the capture groups that result in a successful match will create a corresponding key in the dictionary.</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta">HTTP URL&hellip;</span></span></div>NSString *searchString = <span class="softNobr">@&quot;http://johndoe:secret@www.example.com:8080/private/mail/index.html&quot;;</span> NSString *regexString = <span class="softNobr">@&quot;\\b(https?)://(?:(\\S+?)(?::(\\S+?))?@)?([a-zA-Z0-9\\-.]+)(?::(\\d+))?((?:/[a-zA-Z0-9\\-._?,&#39;+\\&amp;%$=~*!():@\\\\]*)+)?&quot;;</span> if([searchString isMatchedByRegex:regexString]) { NSString *protocolString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:1L];</span> NSString *userString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:2L];</span> NSString *passwordString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:3L];</span> NSString *hostString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:4L];</span> NSString *portString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:5L];</span> NSString *pathString = [searchString <span class="softNobr">stringByMatching:regexString</span> <span class="softNobr">capture:6L];</span> NSMutableDictionary *urlDictionary = <span class="softNobr">[NSMutableDictionary dictionary];</span> if(protocolString) { [urlDictionary <span class="softNobr">setObject:protocolString</span> <span class="softNobr">forKey:@&quot;protocol&quot;];</span> } if(userString) { [urlDictionary <span class="softNobr">setObject:userString</span> <span class="softNobr">forKey:@&quot;user&quot;];</span> } if(passwordString) { [urlDictionary <span class="softNobr">setObject:passwordString</span> <span class="softNobr">forKey:@&quot;password&quot;];</span> } if(hostString) { [urlDictionary <span class="softNobr">setObject:hostString</span> <span class="softNobr">forKey:@&quot;host&quot;];</span> } if(portString) { [urlDictionary <span class="softNobr">setObject:portString</span> <span class="softNobr">forKey:@&quot;port&quot;];</span> } if(pathString) { [urlDictionary <span class="softNobr">setObject:pathString</span> <span class="softNobr">forKey:@&quot;path&quot;];</span> } NSLog(@&quot;urlDictionary: %@&quot;, urlDictionary); }</div> <p><span class="rkl">RegexKit<i>Lite</i></span> 4.0 adds a new method, <span class="code">dictionaryByMatchingRegex:&hellip;</span>, that makes the creation of <span class="code">NSDictionary</span> objects like this much easier, as the following example demonstrates:</p> <div class="box sourcecode"><div class="metainfo noPrintBorder"><span class="entry description"><span class="item meta"><span class="rkl">RegexKit<i>Lite</i></span> &ge; 4.0 example&hellip;</span></span></div>NSString *searchString = <span class="softNobr">@&quot;http://johndoe:secret@www.example.com:8080/private/mail/index.html&quot;;</span> NSString *regexString = <span class="softNobr">@&quot;\\b(https?)://(?:(\\S+?)(?::(\\S+?))?@)?([a-zA-Z0-9\\-.]+)(?::(\\d+))?((?:/[a-zA-Z0-9\\-._?,&#39;+\\&amp;%$=~*!():@\\\\]*)+)?&quot;;</span> NSDictionary *urlDictionary = [searchString <span class="softNobr">dictionaryByMatchingRegex:regexString</span> <span class="softNobr">withKeysAndCaptures:@&quot;protocol&quot;, 1,</span> <span class="softNobr">@&quot;user&quot;, 2,</span> <span class="softNobr">@&quot;password&quot;, 3,</span> <span class="softNobr">@&quot;host&quot;, 4,</span> <span class="softNobr">@&quot;port&quot;, 5,</span> <span class="softNobr">@&quot;path&quot;, 6,</span> <span class="softNobr">NULL];</span> if(urlDictionary != NULL) {<span class="softNobr"> NSLog(@&quot;urlDictionary: %@&quot;, urlDictionary);</span> }</div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>Other than the difference in mutability for the dictionary containing the result, the <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0</span> <span class="code">dictionaryByMatchingRegex:&hellip;</span> example produces the same result as the more verbose, <span class="hardNobr">pre-4.0</span> example.</p> </div></div></div></div> <p>These examples can form the basis of a function or method that takes a <span class="code">NSString</span> as an argument and returns a <span class="code">NSDictionary</span> as a result, maybe even as a category addition to <span class="code">NSString</span>. The following is the output when the examples above are compiled and run:</p> <div class="box shell"><span class="shellOutput">shell% </span><span class="userInput">./http_example<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2008-09-01 10:57:55.245 test_nsstring[31306:807] urlDictionary: { host = &quot;www.example.com&quot;; password = secret; path = &quot;/private/mail/index.html&quot;; port = 8080; protocol = http; user = johndoe; } shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div> </div> <div class="printPageBreakAfter"> <h2 id="AddingRegexKitLitetoyourProject">Adding <span class="rkl">RegexKit<i>Lite</i></span> to your Project</h2> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>The following outlines a typical set of steps that one would perform. This is not the only way, nor the required way to add <span class="rkl">RegexKit<i>Lite</i></span> to your application. They may not be correct for your project as each project is unique. They are an overview for those unfamiliar with adding additional shared libraries to the list of libraries your application links against.</p> </div></div></div></div> <h3 id="AddingtheRegexKitframeworktoyourProject_OutlineofRequiredSteps">Outline of Required Steps</h3> <p>The following outlines the steps required to use <span class="rkl">RegexKit<i>Lite</i></span> in your project.</p> <ul class="square"> <li>Linking your application to the ICU dynamic shared library.</li> <li>Adding the <span class="file">RegexKitLite.m</span> and <span class="file">RegexKitLite.h</span> files to your project and application target.</li> <li>Import the <span class="file">RegexKitLite.h</span> header.</li> </ul> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/XcodeBuildSystem/500-Linking/bs_linking.html" class="section-link printURL">Xcode Build System Guide - Linking</a></li> </ul> </div> <h4 id="AddingRegexKitLitetoyourProject_AddingRegexKitLiteusingXcode">Adding <span class="rkl">RegexKit<i>Lite</i></span> using Xcode</h4> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">These instructions apply to <span class="hardNobr">Xcode versions 2.4.1 and 3.0.</span> Other versions should be similar, but may vary for specific details.</div></div></div></div> <p>Unfortunately, adding additional dynamic shared libraries that your application links to is not a straightforward process in Xcode, nor is there any recommended standard way. Two options are presented below&mdash; the first is the &#39;easy&#39; way that alters your applications Xcode build settings to pass an additional command line argument directly to the linker. The second option attempts to add the ICU dynamic shared library to the list of resources for your project and configuring your executable to link against the added resource.</p> <p>The &#39;easy&#39; way is the recommended way to link against the ICU dynamic shared library.</p> <h5>The Easy Way To Add The ICU Library</h5> <ol> <li><p>First, determine the build settings layer of your project that should have altered linking configuration change applied to. The build settings in Xcode are divided in to layers and each layer inherits the build settings from the layer above it. The top, global layer is <span class="context-menu">Project Settings</span>, followed by <span class="context-menu">Target Settings</span>, and finally the most specific layer <span class="context-menu">Executable Settings</span>. If your project is large enough to have multiple targets and executables, you probably have an idea which layer is appropriate. If you are unsure or unfamiliar with the different layers, <span class="context-menu">Target Settings</span> is recommended.</p></li> <li><p>Select the appropriate layer from the <span class="context-menu">Project</span> menu. If you are unsure, <span class="context-menu hardNobr">Project </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Edit Active Target</span> is recommended.</p></li> <li><p>Select <span class="context-menu">Build</span> from the tab near the top of the <span class="context-menu">Target Info</span> window. Find the <span class="code hardNobr">Other Linker Flags</span> build setting from the many build settings available and edit it. Add <span class="consoleText hardNobr">-licucore</span> <span class="hardNobr"><b>[</b><i>dash</i> <i>ell</i> <i>icucore</i></span> as a single word, without <span class="hardNobr">spaces<b>]</b>.</span> If there are already other flags present, it is recommended that you add <span class="consoleText hardNobr">-licucore</span> to the end of the existing flags.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">If other linker flags are present, there must be at least one space separating <span class="consoleText hardNobr">-licucore</span> from the other linker flags. For example, <span class="consoleText hardNobr">-flag1 -licucore -flag2</span></div></div></div></div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell">The <span class="context-menu">Configuration</span> drop down menu controls which build configuration the changes you make are applied to. <span class="context-menu hardNobr">All Configurations</span> should be selected if this is the first time your are making these changes.</div></div></div></div> </li> <li>Follow the <span class="section-link">Add The <span class="rkl">RegexKit<i>Lite</i></span> Source Files To Your Project</span> steps below.</li> </ol> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/XcodeBuildSystem/300-Build_Settings/bs_build_settings.html" class="section-link">Xcode Build System Guide - Build Settings</a></li> </ul> </div> <h5>The Hard Way To Add The ICU Library</h5> <ol> <li><p>First, add the ICU dynamic shared library to your Xcode project. You may choose to add the library to any group in your project, and which groups are created by default is dependent on the template type you chose when you created your project. For a typical Cocoa application project, a good choice is the <span class="xcode-group">Frameworks</span> group. To add the ICU dynamic shared library, control/right-click on the <span class="xcode-group">Framework</span> group and choose <span class="context-menu">Add </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Existing Files&hellip;</span></p></li> <li><p>Next, you will need to choose the ICU dynamic shared library file to add. Exactly which file to choose depends on your project, but a fairly safe choice is to select <span class="file">/Developer/SDKs/MacOSX10.6.sdk/usr/lib/libicucore.dylib</span>. You may have installed your developer tools in a different location than the default <span class="file">/Developer</span> directory, and the <span class="hardNobr">Mac OS X</span> SDK version should be the one your project is targeting, typically the latest one available.</p></li> <li><p>Then, in the dialog that follows, make sure that <span class="dialog-option">Copy items into&hellip;</span> is unselected. Select the targets you will be using <span class="rkl">RegexKit<i>Lite</i></span> in and then click <span class="context-menu">Add</span> to add the ICU dynamic shared library to your project.</p></li> <li><p>Once the ICU dynamic shared library is added to your project, you will need to add it to the libraries that your executable is linked with. To do so, expand the <span class="xcode-group">Targets</span> group, and then expand the executable targets you will be using <span class="rkl">RegexKit<i>Lite</i></span> in. You will then need to select the <span class="file">libicucore.dylib</span> file that you added in the previous step and drag it in to the <span class="xcode-group">Link Binary With Libraries</span> group for each executable target that you will be using <span class="rkl">RegexKit<i>Lite</i></span> in. The order of the files within the <span class="xcode-group">Link Binary With Libraries</span> group is not important, and for a typical Cocoa application the group will contain the <span class="file">Cocoa.framework</span> file.</p></li> </ol> <h5>Add The <span class="rkl">RegexKit<i>Lite</i></span> Source Files To Your Project</h5> <ol> <li><p>Next, add the <span class="rkl">RegexKit<i>Lite</i></span> source files to your Xcode project. In the <span class="xcode-group">Groups &amp; Files</span> outline view on the left, <span class="hardNobr">control/right-click</span> on the group that would like to add the files to, then select <span class="hardNobr"><span class="context-menu">Add </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Existing Files&hellip;</span></span></p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>You can perform the following steps once for each file (<span class="file">RegexKitLite.h</span> and <span class="file">RegexKitLite.m</span>), or once by selecting both files from the file dialog.</p> </div></div></div></div> </li> <li><p>Select the <span class="file">RegexKitLite.h</span> and / or <span class="file">RegexKitLite.m</span> file from the file chooser dialog.</p></li> <li><p>The next dialog will present you with several options. If you have not already copied the <span class="rkl">RegexKit<i>Lite</i></span> files in to your projects directory, you may want to click on the <span class="dialog-option">Copy items into&hellip;</span> option. Select the targets that you would like add the <span class="rkl">RegexKit<i>Lite</i></span> functionality to.</p></li> <li><p>Finally, you will need to include the <span class="file">RegexKitLite.h</span> header file. The best way to do this is very dependent on your project. If your project consists of only half a dozen source files, you can add:</p> <div class="box sourcecode">#import "RegexKitLite.h"</div> <p>manually to each source file that makes uses of <span class="hardNobr">RegexKit<i class="rk">Lites</i></span> features. If your project has grown beyond this, you&#39;ve probably already organized a common <span class="hardNobr">"master"</span> header to include to capture headers that are required by nearly all source files already.</p></li> </ol> <h4 id="AddingRegexKitLitetoyourProject_AddingRegexKitLiteusingtheShell">Adding <span class="rkl">RegexKit<i>Lite</i></span> using the Shell</h4> <p>Using <span class="rkl">RegexKit<i>Lite</i></span> from the shell is also easy. Again, you need to add the header <span class="code hardNobr">#import</span> to the appropriate source files. Then, to link to the ICU library, you typically only need to add <span class="code hardNobr">-licucore</span>, just as you would any other library. Consider the following example:</p> <div class="box sourcecode"><div class="metainfo printShadow"><span class="entry filename"><span class="item meta">File name:</span><span class="item info">link_example.m</span></span></div>#import &lt;Foundation/NSObjCRuntime.h&gt; #import &lt;Foundation/NSAutoreleasePool.h&gt; #import &quot;RegexKitLite.h&quot; int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [<span class="hardNobr">[NSAutoreleasePool alloc]</span> <span class="hardNobr">init];</span> // <span class="comment">Copyright COPYRIGHT_SIGN APPROXIMATELY_EQUAL_TO 2008</span> // <span class="comment">Copyright \u00a9 \u2245 2008</span> char *utf8CString = <span class="hardNobr">&quot;Copyright \xC2\xA9 \xE2\x89\x85 2008&quot;;</span> NSString *regexString = @&quot;Copyright (.*) (\\d+)&quot;; NSString *subjectString = [NSString <span class="hardNobr">stringWithUTF8String:utf8CString];</span> NSString *matchedString = [subjectString <span class="hardNobr">stringByMatching:regexString</span> <span class="hardNobr">capture:1L];</span> NSLog(@&quot;subject: \&quot;%@\&quot;&quot;, subjectString); NSLog(@&quot;matched: \&quot;%@\&quot;&quot;, matchedString); [pool release]; return(0); }</div> <p>Compiled and run from the shell:</p> <div class="box shell"><span class="shellOutput">shell% </span><span class="userInput">cd examples<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">shell% </span><span class="userInput">gcc -g -I.. -o link_example link_example.m <span class="hardNobr">../RegexKitLite.m</span> <span class="hardNobr">-framework Foundation</span> <span class="hardNobr">-licucore<span class="return" title="Return key">&crarr;</span></span></span> <span class="shellOutput">shell% </span><span class="userInput">./link_example<span class="return" title="Return key">&crarr;</span></span> <span class="shellOutput">2008-03-14 03:52:51.187 test[15283:807] subject: &quot;Copyright &copy; &cong; 2008&quot; 2008-03-14 03:52:51.269 test[15283:807] matched: &quot;&copy; &cong;&quot; shell% </span><span class="cursor" title="Shell cursor">&#9612;</span></div></div> <div class="reference printPageBreakAfter"> <h1 class="reference" id="RegexKitLiteNSStringAdditionsReference"><span class="rkl">RegexKit<i>Lite</i></span> NSString Additions Reference</h1> <div class="box classSpecs hasRows zebraRows"> <div class="row odd"><span class="cell left hardNobr">Extends by category</span><span class="cell right lastCell"><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html">NSString</a>, <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/index.html">NSMutableString</a></span></div> <div class="row even regexKitVersion"><span class="cell left hardNobr"><span class="rkl">RegexKit<i>Lite</i></span></span><span class="cell right lastCell"><span class="version">4.0</span></span></div> <div class="row odd"><span class="cell left hardNobr">Declared in</span><ul class="cell right lastCell"><li>RegexKitLite.h</li></ul></div> <div class="row even lastRow"><span class="cell left hardNobr">Companion guides</span> <ul class="cell right lastCell"> <li><a href="http://userguide.icu-project.org/strings/regexp" class="printURL">ICU User Guide - Regular Expressions</a></li> </ul></div> </div> <h2>Overview</h2> <p><span class="rkl">RegexKit<i>Lite</i></span> is not meant to be a full featured regular expression framework. Because of this, it provides only the basic primitives needed to create additional functionality. It is ideal for developers who:</p> <ul class="square"> <li>Developing applications for the iPhone.</li> <li>Have modest regular expression needs.</li> <li>Require a very small footprint.</li> <li>Unable or unwilling to add additional, external frameworks.</li> <li>Deal predominantly in <span class="code hardNobr">UTF-16</span> encoded Unicode strings.</li> <li>Require the enhanced word breaking functionality provided by the ICU library.</li> </ul> <p><span class="rkl">RegexKit<i>Lite</i></span> consists of only two files, the header file <span class="file">RegexKitLite.h</span> and <span class="file">RegexKitLite.m</span>. The only other requirement is to link with the ICU library that comes with <span class="hardNobr">Mac OS X.</span> No new classes are created, all functionality is provided as a category extension to the <span class="code">NSString</span> and <span class="code">NSMutableString</span> classes.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#RegexKitLiteGuide" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> Guide</a></li> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> <li><a href="#AddingRegexKitLitetoyourProject" class="section-link">Adding <span class="rkl">RegexKit<i>Lite</i></span> to your Project</a></li> <li><a href="#LicenseInformation" class="section-link">License Information</a></li> <li><a href="http://regexkit.sourceforge.net/" class="section-link printURL">RegexKit Framework</a></li> <li><a href="http://site.icu-project.org/" class="section-link printURL">International Components for Unicode</a></li> <li><a href="http://www.unicode.org/" class="section-link printURL">Unicode Home Page</a></li> </ul> </div> <h3 id="NSString_RegexKitLiteAdditions__CompileTimePreprocessorTunables">Compile Time Preprocessor Tunables</h3> <p>The settings listed below are implemented using the C Preprocessor. Some of the setting are simple boolean <span class="code">enabled</span> or <span class="code">disabled</span> settings, while others specify a value, such as the number of cached compiled regular expressions. There are several ways to alter these settings, but if you are not familiar with this style of compile time configuration settings and how to alter them using the C Preprocessor, it is recommended that you use the default values provided.</p> <table class="standard cppTunables" summary="Compile Time Preprocessor Tunables"> <tr><th>Setting</th><th>Default</th><th>Description</th></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">NS_&#8203;BLOCK_&#8203;ASSERTIONS</span><span class="cpp_flag softNobr tbrOff">NS_BLOCK_ASSERTIONS</span></span></td><td><i>n/a</i></td><td><span class="rkl">RegexKit<i>Lite</i></span> contains a number of extra run-time assertion checks that can be disabled with this flag. The standard <span class="file">NSException.h</span> assertion macros are not used because of the multithreading lock. This flag is typically set for <span class="context-menu">Release</span> style builds where the additional error checking is no longer necessary.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;APPEND_&#8203;TO_&#8203;ICU_&#8203;FUNCTIONS</span><span class="cpp_flag softNobr tbrOff">RKL_APPEND_TO_ICU_FUNCTIONS</span></span></td><td><i>None</i></td><td>This flag is useful if you are supplying your own version of the ICU library. When set, this preprocessor define causes the ICU functions used by <span class="rkl">RegexKit<i>Lite</i></span> to have the value of <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;APPEND_&#8203;TO_&#8203;ICU_&#8203;FUNCTIONS</span><span class="cpp_flag softNobr tbrOff">RKL_APPEND_TO_ICU_FUNCTIONS</span></span> appended to them. For example, if <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;APPEND_&#8203;TO_&#8203;ICU_&#8203;FUNCTIONS</span><span class="cpp_flag softNobr tbrOff">RKL_APPEND_TO_ICU_FUNCTIONS</span></span> is set to <span class="code">_4_0</span> <span class="softNobr">(i.e., <span><span class="consoleText tbrOn">-DRKL_&#8203;APPEND_&#8203;TO_&#8203;ICU_&#8203;FUNCTIONS=_4_0</span><span class="consoleText tbrOff">-DRKL_APPEND_TO_ICU_FUNCTIONS=_4_0</span></span>),</span> it would cause <span class="code">uregex_find()</span> to become <span class="code">uregex_find_4_0()</span>.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;BLOCKS</span><span class="cpp_flag softNobr tbrOff">RKL_BLOCKS</span></span></td><td><i>Automatic</i></td><td> Enables blocks support. This feature is automatically enabled if <span><span class="cpp_flag softNobr tbrOn">NS_&#8203;BLOCKS_&#8203;AVAILABLE</span><span class="cpp_flag softNobr tbrOff">NS_BLOCKS_AVAILABLE</span></span> is set to <span class="code">1</span>, which is typically set if support for blocks is appropriate. At the time of this writing, this typically means that the Xcode setting for the minimum version of <span class="hardNobr">Mac OS X</span> supported must be <span class="hardNobr">10.6</span>. This feature may be explicitly disabled under all circumstances by setting its value to <span class="code">0</span>, or alternatively it can be explicitly enabled under all circumstances by setting its value to <span class="code">1</span>. The behavior is undefined if <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;BLOCKS</span><span class="cpp_flag softNobr tbrOff">RKL_BLOCKS</span></span> is set to <span class="code">1</span> and the compiler does not support the blocks language extension or if the run-time does not support blocks.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;CACHE_&#8203;SIZE</span><span class="cpp_flag softNobr tbrOff">RKL_CACHE_SIZE</span></span></td><td><span class="code">13</span></td> <td><span class="rkl">RegexKit<i>Lite</i></span> uses a 4-way set associative cache and <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;CACHE_&#8203;SIZE</span><span class="cpp_flag softNobr tbrOff">RKL_CACHE_SIZE</span></span> controls the number of sets in the cache. The total number of compiled regular expressions that can be cached is <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;CACHE_&#8203;SIZE</span><span class="cpp_flag softNobr tbrOff">RKL_CACHE_SIZE</span></span> * <span class="code">4</span>, for a default value of <span class="code">52</span>. <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;CACHE_&#8203;SIZE</span><span class="cpp_flag softNobr tbrOff">RKL_CACHE_SIZE</span></span> should always be a prime number to maximize the use of the cache.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;DTRACE</span><span class="cpp_flag softNobr tbrOff">RKL_DTRACE</span></span></td><td><i>Disabled</i></td><td>This preprocessor define controls whether or not <span class="rkl">RegexKit<i>Lite</i></span> provider DTrace probe points are enabled. This feature may be explicitly disabled under all circumstances by setting its value to <span class="code">0</span>.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;FAST_&#8203;MUTABLE_&#8203;CHECK</span><span class="cpp_flag softNobr tbrOff">RKL_FAST_MUTABLE_CHECK</span></span></td><td><i>Disabled</i></td><td>Enables the use of the undocumented, private <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> <span class="code hardNobr">__CFStringIsMutable()</span> function to determine if the string to be searched is immutable. This can significantly increase the number of matches per second that can be performed on immutable strings since a number of mutation checks can be safely skipped.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;FIXED_&#8203;LENGTH</span><span class="cpp_flag softNobr tbrOff">RKL_FIXED_LENGTH</span></span></td><td><span class="code">2048</span></td><td>Sets the size of the fixed length <span class="code hardNobr">UTF-16</span> conversion cache buffer. Strings that need to be converted to <span class="code">UTF-16</span> that have a length less than this size will use the fixed length conversion cache. Using a fixed sized buffer for all small strings means less <span class="code">malloc()</span> overhead, heap fragmentation, and reduces the chances of a memory leak occurring.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;METHOD_&#8203;PREPEND</span><span class="cpp_flag softNobr tbrOff">RKL_METHOD_PREPEND</span></span></td><td><i>None</i></td><td>When set, this preprocessor define causes the <span class="rkl">RegexKit<i>Lite</i></span> methods defined in <span class="file">RegexKitLite.h</span> to have the value of <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;METHOD_&#8203;PREPEND</span><span class="cpp_flag softNobr tbrOff">RKL_METHOD_PREPEND</span></span> prepended to them. For example, if <span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;METHOD_&#8203;PREPEND</span><span class="cpp_flag softNobr tbrOff">RKL_METHOD_PREPEND</span></span> is set to <span class="code">xyz_</span> <span class="softNobr">(i.e., <span><span class="consoleText tbrOn">-DRKL_&#8203;METHOD_&#8203;PREPEND=xyz_</span><span class="consoleText tbrOff">-DRKL_METHOD_PREPEND=xyz_</span></span>),</span> it would cause <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">clearStringCache</a> to become <span class="code">xyz_clearStringCache</span>.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;REGISTER_&#8203;FOR_&#8203;IPHONE_&#8203;LOWMEM_&#8203;NOTIFICATIONS</span><span class="cpp_flag softNobr tbrOff">RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS</span></span></td><td><i>Automatic</i></td><td>This preprocessor define controls whether or not extra code is included that attempts to automatically register with the <span class="code">NSNotificationCenter</span> for the <span><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/c/data/UIApplicationDidReceiveMemoryWarningNotification" class="code tbrOn">UIApplication&#8203;DidReceive&#8203;MemoryWarning&#8203;Notification</a><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/c/data/UIApplicationDidReceiveMemoryWarningNotification" class="code tbrOff">UIApplicationDidReceiveMemoryWarningNotification</a></span> notification. This feature is automatically enabled if it can be determined at compile time that the iPhone is being targeted. This feature may be explicitly disabled under all circumstances by setting its value to <span class="code">0</span>.</td></tr> <tr><td><span><span class="cpp_flag softNobr tbrOn">RKL_&#8203;STACK_&#8203;LIMIT</span><span class="cpp_flag softNobr tbrOff">RKL_STACK_LIMIT</span></span></td><td><span class="code">131072</span></td><td>The maximum amount of stack space that will be used before switching to heap based allocations. This can be useful for multithreading programs where the stack size of secondary threads is much smaller than the main thread.</td></tr> </table> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Assertions/Tasks/AssertMacros.html" class="section-link printURL_small">Assertions and Logging - Using the Assertion Macros</a></li> </ul> </div> <h4>Fast Mutable Checks</h4> <p>Setting <span class="cpp_flag">RKL_FAST_MUTABLE_CHECK</span> allows <span class="rkl">RegexKit<i>Lite</i></span> to quickly check if a string to search is immutable or not. Every call to <span class="rkl">RegexKit<i>Lite</i></span> requires checking a strings <span class="code">hash</span> and <span class="code">length</span> values to guard against a string mutating and using invalid cached data. If the same string is searched repeatedly and it is immutable, these checks aren&#39;t necessary since the string can never change while in use. While these checks are fairly quick, it can add approximately 15 to 20 percent of extra overhead, and not performing the checks is always faster.</p> <p>Since checking a strings mutability requires calling an undocumented, private <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> function, <span class="rkl">RegexKit<i>Lite</i></span> takes extra precautions and does not use the function directly. Instead, an internal, local stub function is created and called to determine if a string is mutable. The first time this function is called, <span class="rkl">RegexKit<i>Lite</i></span> uses <span class="code hardNobr">dlsym()</span> to look up the address of the <span class="code hardNobr">__CFStringIsMutable()</span> function. If the function is found, <span class="rkl">RegexKit<i>Lite</i></span> will use it from that point on to determine if a string is immutable. However, if the function is not found, <span class="rkl">RegexKit<i>Lite</i></span> has no way to determine if a string is mutable or not, so it assumes the worst case that all strings are potentially mutable. This means that the private <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> <span class="code hardNobr">__CFStringIsMutable()</span> function can go away at any time and <span class="rkl">RegexKit<i>Lite</i></span> will continue to work, although with slightly less performance.</p> <p>This feature is disabled by default, but should be fairly safe to enable due to the extra precautions that are taken. If this feature is enabled and the <span class="code hardNobr">__CFStringIsMutable()</span> function is not found for some reason, <span class="rkl">RegexKit<i>Lite</i></span> falls back to its default behavior which is the same as if this feature was not enabled.</p> <h4>iPhone Low Memory Notifications</h4> <p>The <span class="cpp_flag">RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS</span> preprocessor define controls whether or not extra code is compiled in that automatically registers for the iPhone UIKit <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/c/data/UIApplicationDidReceiveMemoryWarningNotification" class="code">UIApplicationDidReceiveMemoryWarningNotification</a> notification. When enabled, an initialization function tagged with <span class="code">__attribute__((constructor))</span> is executed by the linker at load time which causes <span class="rkl">RegexKit<i>Lite</i></span> to check if the low memory notification symbol is available. If the symbol is present then <span class="rkl">RegexKit<i>Lite</i></span> registers to receive the notification. When the notification is received, <span class="rkl">RegexKit<i>Lite</i></span> will automatically call <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">clearStringCache</a> to flush the caches and return the memory used to hold any cached compiled regular expressions.</p> <p>This feature is normally automatically enabled if it can be determined at compile time that the iPhone is being targeted. This feature is safe to enable even if the target is Mac OS X for the desktop. It can also be explicitly disabled, even when targeting the iPhone, by setting <span class="cpp_flag">RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS</span> to <span class="code">0</span> <span class="hardNobr">(i.e., <span class="consoleText">-DRKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS=0</span>).</span></p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/iphone/library/documentation/Performance/Conceptual/ManagingMemory/Articles/MemoryAlloc.html#//apple_ref/doc/uid/20001881-SW1" class="section-link printURL_small">Memory Usage Performance Guidelines - Responding to Low-Memory Warnings in iPhone OS</a></li> </ul> </div> <h4>Using <span class="rkl">RegexKit<i>Lite</i></span> with a Custom ICU Build</h4> <p>The details of building and linking to a custom build of ICU will not be covered here. ICU is a very large and complex library that can be configured and packaged in countless ways. Building and linking your application to a custom build of ICU is <i><b>non&#8209;trivial</b></i>. Apple provides the full source to the version of ICU that they supply with <span class="hardNobr">Mac OS X.</span> At the time of this writing, the latest version available was for <span class="hardNobr">Mac OS X 10.6.2&mdash;</span> <a href="http://www.opensource.apple.com/tarballs/ICU/ICU-400.38.tar.gz" class="file printURL">ICU-400.38.tar.gz</a>.</p> <p><span class="rkl">RegexKit<i>Lite</i></span> provides the <span class="cpp_flag">RKL_APPEND_TO_ICU_FUNCTIONS</span> pre-processor define if you would like to use <span class="rkl">RegexKit<i>Lite</i></span> with a custom ICU build that you supply. A custom version of ICU will typically have the ICU version appended to all of its functions, and <span class="cpp_flag">RKL_APPEND_TO_ICU_FUNCTIONS</span> allows you to append that version to the ICU functions that <span class="rkl">RegexKit<i>Lite</i></span> calls. For example, passing <span class="hardNobr consoleText">-DRKL_APPEND_TO_ICU_FUNCTIONS=_4_0</span> to <span class="consoleText">gcc</span> would cause the ICU function <span class="hardNobr code">uregex_find()</span> used by <span class="rkl">RegexKit<i>Lite</i></span> to be called as <span class="hardNobr code">uregex_find_4_0()</span>.</p> <h3 id="NSString_RegexKitLiteAdditions__Xcode3IntegratedDocumentation">Xcode 3 Integrated Documentation</h3> <p>This documentation is available in the Xcode DocSet format at the following URL:</p> <p class="indent"><span class="code">feed://regexkit.sourceforge.net/RegexKitLiteDocSets.atom</span></p> <p>For Xcode &lt; 3.2, select <span class="context-menu">Help </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Documentation</span>. Then, in the lower left hand corner of the documentation window, there should be a gear icon with a drop down menu indicator which you should select and choose <span class="context-menu">New Subscription&hellip;</span> and enter the DocSet URL.</p> <p>For Xcode &ge; 3.2, select <span class="context-menu">Xcode </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Preferences&hellip;</span>. Then select the <span class="context-menu">Documentation</span> preference group, typically the right most group, and press <span class="context-menu">Add Documentation Set Publisher&hellip;</span> and enter the DocSet URL.</p> <p>Once you have added the URL, a new group should appear, inside which will be the <span class="rkl">RegexKit<i>Lite</i></span> documentation with a <span class="xcode-button">Get</span> button. Click on the <span class="xcode-button">Get</span> button and follow the prompts.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>Xcode will ask you to enter an administrators password to install the documentation, which is explained <a href="http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/Documentation_Sets/070-Acquiring_Documentation_Sets_Through_Web_Feeds/acquiring_docsets.html#//apple_ref/doc/uid/TP40005266-CH10-SW9" class="printURL_small">here</a>.</p> </div></div></div></div> <h3 id="NSString_RegexKitLiteAdditions__CachedInformationandMutableStrings">Cached Information and Mutable Strings</h3> <p>While <span class="rkl">RegexKit<i>Lite</i></span> takes steps to ensure that the information it has cached is valid for the strings it searches, there exists the possibility that out of date cached information may be used when searching mutable strings. For each compiled regular expression, <span class="rkl">RegexKit<i>Lite</i></span> caches the following information about the last <span class="code">NSString</span> that was searched:</p> <ul class="square"> <li>The strings <span class="code">length</span>, <span class="code">hash</span> value, and the pointer to the <span class="code">NSString</span> object.</li> <li>The pointer to the <span class="code hardNobr">UTF-16</span> buffer that contains the contents of the string, which may be an internal buffer if the string required conversion.</li> <li>The <span class="code">NSRange</span> used for the <span class="code">inRange:</span> parameter for the last search, and the <span class="code">NSRange</span> result for capture <span class="code">0</span> of that search.</li> </ul> <p>An ICU compiled regular expression must be <span class="hardNobr">&quot;set&quot;</span> to the text to be searched. Before a compiled regular expression is used, the pointer to the string object to search, its <span class="code">hash</span>, <span class="code">length</span>, and the pointer to the <span class="code">UTF-16</span> buffer is compared with the values that the compiled regular expression was last <span class="hardNobr">&quot;set&quot;</span> to. If any of these values are different, the compiled regular expression is reset and <span class="hardNobr">&quot;set&quot;</span> to the new string.</p> <p>If a <span class="code">NSMutableString</span> is mutated between two uses of the same compiled regular expression and its <span class="code">hash</span>, <span class="code">length</span>, or <span class="code hardNobr">UTF-16</span> buffer changes between uses, <span class="rkl">RegexKit<i>Lite</i></span> will automatically reset the compiled regular expression with the new values of the mutated string. The results returned will correctly reflect the mutations that have taken place between searches.</p> <p>It is possible that the mutations to a string can go undetected, however. If the mutation keeps the <span class="code">length</span> the same, then the only way a change can be detected is if the strings <span class="code">hash</span> value changes. For most mutations the <span class="code">hash</span> value will change, but it is possible for two different strings to share the same <span class="code">hash</span>. This is known as a <i>hash collision</i>. Should this happen, the results returned by <span class="rkl">RegexKit<i>Lite</i></span> may not be correct.</p> <p>Therefore, if you are using <span class="rkl">RegexKit<i>Lite</i></span> to search <span class="code">NSMutableString</span> objects, and those strings may have mutated in such a way that <span class="rkl">RegexKit<i>Lite</i></span> is unable to detect that the string has changed, you must manually clear the internal cache to ensure that the results accurately reflect the mutations. To clear the cached information for a specific string you send the instance a <a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">flushCachedRegexData</a> message:</p> <div class="box sourcecode">NSMutableString *aMutableString; // <span class="comment">Assumed to be valid.</span> [aMutableString flushCachedRegexData];</div> <p>To clear all of the cached information in <span class="rkl">RegexKit<i>Lite</i></span>, which includes all the cached compiled regular expressions along with any cached information and <span class="hardNobr code">UTF-16</span> conversions for strings that have been searched, you use the following class method:</p> <div class="box sourcecode">[NSString clearStringCache];</div> <div class="box warning"><div class="table"><div class="row"><div class="label cell">Warning:</div><div class="message cell"> <p>When searching <span class="code">NSMutableString</span> objects that have mutated between searches, failure to clear the cache may result in undefined behavior. Use <a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">flushCachedRegexData</a> to selectively clear the cached information about a <span class="code">NSMutableString</span> object.</p> </div></div></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">+ clearStringCache</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">- flushCachedRegexData</a></li> </ul> </div> <h3 id="RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods">Block-based Enumeration Methods</h3> <p>The <span class="rkl">RegexKit<i>Lite</i></span> Block-based enumeration methods are modeled after their <span class="code">NSString</span> counterparts. There are a few differences, however.</p> <ul class="square highlights"> <li><span class="rkl">RegexKit<i>Lite</i></span> does not support mutating a <span class="code">NSMutableString</span> object while it is under going Block-based enumeration.</li> <li>There is no support for concurrent enumeration.</li> </ul> <p>While <span class="rkl">RegexKit<i>Lite</i></span> may not support mutating a <span class="code">NSMutableString</span> during Block-based enumeration, it does provide the means to create a new string from the <span class="code">NSString</span> object returned by the block used to enumerate the matches in a string, and in the case of <span class="code">NSMutableString</span>, to replace the contents of that <span class="code">NSMutableString</span> with the modified string at the end of the enumeration. This functionality is available via the following methods:</p> <ul class="square highlights"> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:" class="code">- stringByReplacingOccurrencesOfRegex:usingBlock:</a> (<span class="code">NSString</span>)</li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:" class="code">- replaceOccurrencesOfRegex:usingBlock:</a> (<span class="code">NSMutableString</span>)</li> </ul> <h4>Exception to the Cocoa Memory Management Rules for Block-based Enumeration</h4> <p>The standard <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html" class="section-link">Cocoa Memory Management Rules</a> specify that objects returned by a method, or in this case the objects passed to a Block, remain valid throughout the scope of the calling method. Due to the potentially large volume of temporary strings that are created during a Block-based enumeration, <span class="rkl">RegexKit<i>Lite</i></span> makes an exception to this rule&ndash; the strings passed to a Block via <span class="argument">capturedStrings</span><span class="code">[]</span> are valid only until the closing brace of the Block:</p> <div class="box sourcecode">[searchString enumerateStringsMatchedByRegex:regex usingBlock: ^(NSInteger captureCount, NSString * const capturedStrings, const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { // <span class="comment">Block code.</span> } /* <span class="comment">&lt;- capturedStrings[] is valid only up to this point.</span> */ ];</div> <p>If you need to refer to a string past the closing brace of the Block, you need to send that string a <span class="code">retain</span> message. Of course, it is not always necessary to explicitly send a <span class="argument">capturedStrings</span><span class="code">[]</span> string a <span class="code">retain</span> message when you need it to exist past the closing brace of a Block&ndash; adding a <span class="argument">capturedStrings</span><span class="code">[]</span> string to a <span class="code">NSMutableDictionary</span> will send the string a <span class="code">retain</span> as a side effect of adding it to the dictionary.</p> <p>Memory management during <span class="rkl">RegexKit<i>Lite</i></span> Block-based enumeration is conceptually similar to the following pseudo-code:</p> <div class="box sourcecode">NSInteger captureCount = [regex captureCount]; while(moreMatches) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; BOOL stop = NO; NSRange capturedRanges[captureCount]; NSString *capturedStrings[captureCount]; for(capture = 0L; capture &lt; captureCount; capture++) { capturedRanges[capture] = [searchString rangeOfRegex:regex capture:capture]; capturedStrings[capture] = [searchString stringByMatching:regex capture:capture]; } // <span class="comment">The following line represents the execution of the user supplied Block.</span> enumerationBlock(captureCount, capturedStrings, capturedRanges, &amp;stop); // <span class="comment">... and this represents when the user supplied Block has finished / returned.</span> [pool release]; // <span class="comment">capturedStrings[] are sent a release at this point.</span> if(stop != NO) { break; } }</div> <p>While conceptually and behaviorally similar, it is important to note that <span class="rkl">RegexKit<i>Lite</i></span> does not actually use or create autorelease pools when performing Block-based enumeration. Instead, a <span class="code">CFMutableArray</span> object is used to accumulate the temporary string objects during an iteration, and at the start of an iteration, any previously accumulated temporary string objects are removed from the array.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> </ul> </div> <h3>Usage Notes</h3> <h4>Convenience Methods</h4> <p>For convenience methods where an argument is not present, the default value used is given below.</p> <table class="standard"> <tr><th>Argument</th><th>Default Value</th></tr> <tr><td><span class="code">capture:</span></td><td><span class="code">0</span></td></tr> <tr><td><span class="code">options:</span></td><td><a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a></td></tr> <tr><td><span class="code">range:</span></td><td>The entire range of the receiver.</td></tr> <tr><td><span class="code">enumerationOptions:</span></td><td><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions" class="code">RKLRegexEnumerationNoOptions</a></td></tr> </table> <h4>Exceptions Raised</h4> <p>Methods will raise an exception if their arguments are invalid, such as passing <span class="code">NULL</span> for a required parameter. An invalid regular expression or <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> parameter will not raise an exception. Instead, a <span class="code">NSError</span> object with information about the error will be created and returned via the address given with the optional <span class="argument">error</span> argument. If information about the problem is not required, <span class="argument">error</span> may be <span class="code">NULL</span>. For convenience methods that do not have an <span class="argument">error</span> argument, the primary method is invoked with <span class="code">NULL</span> passed as the argument for <span class="argument">error</span>.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException" class="code">NSInvalidArgumentException</a> if <span class="argument">regex</span> is <span class="code">NULL</span>, or if <span class="hardNobr"><span class="argument">capture</span> &lt; <span class="code">0</span></span> or is not valid for <span class="argument">regex</span>. </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSRangeException" class="code">NSRangeException</a> if <span class="argument">range</span> exceeds the bounds of the receiver. </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSRangeException" class="code">NSRangeException</a> if the receivers length exceeds the maximum value that can be represented by a signed <span class="hardNobr">32-bit</span> integer, even on <span class="hardNobr">64-bit</span> architectures. </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Search and replace methods raise <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> </ul> </div> <h2>Tasks</h2> <div class="tasks"> <div class="header">DTrace Probe Points</div> <ul> <li><a href="#DTrace_RegexKitLiteProbePoints__compiledRegexCache" title="This probe point fires each time the compiled regular expression cache is accessed." class="code">RegexKitLite:::compiledRegexCache</a></li> <li><a href="#DTrace_RegexKitLiteProbePoints__utf16ConversionCache" title="This probe point fires each time the UTF-16 conversion cache is accessed." class="code">RegexKitLite:::utf16ConversionCache</a></li> </ul> </div> <div class="tasks"> <div class="header">Clearing Cached Information</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__.clearStringCache" title="Clears the cached information about strings." class="code">+ clearStringCache</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" title="Clears any cached information about the receiver." class="code">- flushCachedRegexData</a></li> </ul> </div> <div class="tasks"> <div class="header">Determining the Number of Captures</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__.captureCountForRegex:" title="Returns the number of captures that regex contains." class="code">+ captureCountForRegex:</a> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></li> <li><a href="#NSString_RegexKitLiteAdditions__.captureCountForRegex:options:error:" title="Returns the number of captures that regex contains." class="code">+ captureCountForRegex:options:error:</a> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCount" title="Returns the number of captures that regex contains." class="code">- captureCount</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:" title="Returns the number of captures that regex contains." class="code">- captureCountWithOptions:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Finding all Captures of all Matches</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:" title="Returns an array containing all the matches from the receiver that were matched by the regular expression regex. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression." class="code">- arrayOfCaptureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:range:" title="Returns an array containing all the matches from the receiver that were matched by the regular expression regex within range. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression." class="code">- arrayOfCaptureComponentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:options:range:error:" title="Returns an array containing all the matches from the receiver that were matched by the regular expression regex within range using options. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression." class="code">- arrayOfCaptureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Getting all the Captures of a Match</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:" title="Returns an array containing the substrings matched by each capture group present in regex for the first match of regex in the receiver." class="code">- captureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:range:" title="Returns an array containing the substrings matched by each capture group present in regex for the first match of regex within range of the receiver." class="code">- captureComponentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:options:range:error:" title="Returns an array containing the substrings matched by each capture group present in regex for the first match of regex within range of the receiver using options." class="code">- captureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Finding all Matches</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" title="Returns a NSArray containing all the substrings from the receiver that were matched by the regular expression regex." class="code">- componentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:capture:" title="Returns a NSArray containing all the substrings from the receiver that were matched by capture number capture from the regular expression regex." class="code">- componentsMatchedByRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:range:" title="Returns a NSArray containing all the substrings from the receiver that were matched by the regular expression regex within range." class="code">- componentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:options:range:capture:error:" title="Returns a NSArray containing all the substrings from the receiver that were matched by the regular expression regex within range using options." class="code">- componentsMatchedByRegex:options:range:capture:error:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex and executes block for each match found." class="code">- enumerateStringsMatchedByRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex within range using options and executes block using enumerationOptions for each match found." class="code">- enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> </ul> </div> <div class="tasks"> <div class="header">Dividing Strings</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" title="Returns a NSArray containing substrings of the receiver that have been divided by the regular expression regex." class="code">- componentsSeparatedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:range:" title="Returns a NSArray containing substrings within range of the receiver that have been divided by the regular expression regex." class="code">- componentsSeparatedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:options:range:error:" title="Returns a NSArray containing substrings within range of the receiver that have been divided by the regular expression regex using options." class="code">- componentsSeparatedByRegex:options:range:error:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:usingBlock:" title="Enumerates the strings of the receiver that have been divided by the regular expression regex and executes block for each divided string." class="code">- enumerateStringsSeparatedByRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:" title="Enumerates the strings of the receiver that have been divided by the regular expression regex within range using options and executes block using enumerationOptions for each divided string." class="code">- enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> </ul> </div> <div class="tasks"> <div class="header">Identifying Matches</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:" title="Returns a Boolean value that indicates whether the receiver is matched by regex." class="code">- isMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:inRange:" title="Returns a Boolean value that indicates whether the receiver is matched by regex within range." class="code">- isMatchedByRegex:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:options:inRange:error:" title="Returns a Boolean value that indicates whether the receiver is matched by regex within range." class="code">- isMatchedByRegex:options:inRange:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Determining if a Regular Expression is Valid</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isRegexValid" title="Returns a Boolean value that indicates whether the regular expression contained in the receiver is valid." class="code">- isRegexValid</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isRegexValidWithOptions:error:" title="Returns a Boolean value that indicates whether the regular expression contained in the receiver is valid using options." class="code">- isRegexValidWithOptions:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Determining the Range of a Match</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:" title="Returns the range for the first match of regex in the receiver." class="code">- rangeOfRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:capture:" title="Returns the range of capture number capture for the first match of regex in the receiver." class="code">- rangeOfRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:inRange:" title="Returns the range for the first match of regex within range of the receiver." class="code">- rangeOfRegex:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:" title="Returns the range of capture number capture for the first match of regex within range of the receiver." class="code">- rangeOfRegex:options:inRange:capture:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Modifying Mutable Strings</div> <ul> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" title="Replaces all occurrences of the regular expression regex with the contents of replacement string after performing capture group substitutions, returning the number of replacements made." class="code">- replaceOccurrencesOfRegex:withString:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:range:" title="Replaces all occurrences of the regular expression regex within range with the contents of replacement string after performing capture group substitutions, returning the number of replacements made." class="code">- replaceOccurrencesOfRegex:withString:range:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:options:range:error:" title="Replaces all occurrences of the regular expression regex using options within range with the contents of replacement string after performing capture group substitutions, returning the number of replacements made." class="code">- replaceOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex and executes block for each match found. Replaces the characters that were matched with the contents of the string returned by block, returning the number of replacements made." class="code">- replaceOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex within range using options and executes block using enumerationOptions for each match found. Replaces the characters that were matched with the contents of the string returned by block, returning the number of replacements made." class="code">- replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> </ul> </div> <div class="tasks"> <div class="header">Creating Temporary Strings from a Match</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:" title="Returns a string created from the characters of the receiver that are in the range of the first match of regex." class="code">- stringByMatching:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:capture:" title="Returns a string created from the characters of the receiver that are in the range of the first match of regex for capture." class="code">- stringByMatching:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:inRange:" title="Returns a string created from the characters of the receiver that are in the range of the first match of regex within range of the receiver." class="code">- stringByMatching:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:options:inRange:capture:error:" title="Returns a string created from the characters of the receiver that are in the range of the first match of regex using options within range of the receiver for capture." class="code">- stringByMatching:options:inRange:capture:error:</a></li> </ul> </div> <div class="tasks"> <div class="header">Replacing Substrings</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" title="Returns a string created from the characters of the receiver in which all matches of the regular expression regex are replaced with the contents of the replacement string after performing capture group substitutions." class="code">- stringByReplacingOccurrencesOfRegex:withString:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:range:" title="Returns a string created from the characters within range of the receiver in which all matches of the regular expression regex are replaced with the contents of the replacement string after performing capture group substitutions." class="code">- stringByReplacingOccurrencesOfRegex:withString:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:options:range:error:" title="Returns a string created from the characters within range of the receiver in which all matches of the regular expression regex using options are replaced with the contents of the replacement string after performing capture group substitutions." class="code softNobr">- stringByReplacingOccurrencesOfRegex:&#8203;withString:options:range:error:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex and executes block for each match found. Returns a string created by replacing the characters that were matched in the receiver with the contents of the string returned by block." class="code">- stringByReplacingOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:" title="Enumerates the matches in the receiver by the regular expression regex within range using options and executes block using enumerationOptions for each match found. Returns a string created by replacing the characters that were matched in the receiver with the contents of the string returned by block." class="code">- stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> </ul> </div> <div class="tasks"> <div class="header">Creating a Dictionary from a Match</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:withKeysAndCaptures:" class="code" title="Creates and returns a dictionary containing the matches constructed from the specified set of keys and captures for the first match of regex in the receiver.">- dictionaryByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:range:withKeysAndCaptures:" class="code" title="Creates and returns a dictionary containing the matches constructed from the specified set of keys and captures for the first match of regex within range of the receiver.">- dictionaryByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:" class="code" title="Creates and returns a dictionary containing the matches constructed from the specified set of keys and captures for the first match of regex within range of the receiver using options.">- dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> </ul> </div> <div class="tasks"> <div class="header">Creating a Dictionary from every Match</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:" title="Returns an array containing all the matches in the receiver that were matched by the regular expression regex. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of keys and captures." class="code">- arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:" title="Returns an array containing all the matches in the receiver that were matched by the regular expression regex within range. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of keys and captures." class="code">- arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:" title="Returns an array containing all the matches in the receiver that were matched by the regular expression regex within range using options. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of keys and captures." class="code">- arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> </ul> </div> <h2>DTrace Probe Points</h2> <div class="block dtrace"> <div class="section name softNobr" id="DTrace_RegexKitLiteProbePoints__compiledRegexCache">RegexKitLite:::compiledRegexCache</div> <div class="section summary">This probe point fires each time the compiled regular expression cache is accessed.</div> <div class="signature"><span class="hardNobr"><span class="function">RegexKitLite:::compiledRegexCache</span>(</span><span class="hardNobr">unsigned long <span class="argument">eventID</span>,</span> <span class="hardNobr">const char *<span class="argument">regexUTF8</span>,</span> <span class="hardNobr">int <span class="argument">options</span>,</span> <span class="hardNobr">int <span class="argument">captures</span>,</span> <span class="hardNobr">int <span class="argument">hitMiss</span>,</span> <span class="hardNobr">int <span class="argument">icuStatusCode</span>,</span> <span class="hardNobr">const char *<span class="argument">icuErrorMessage</span>,</span> <span class="hardNobr">double *<span class="argument">hitRate</span>);</span></div> <div class="section parameters"><div class="header">Arguments</div> <ul> <li> <div><span class="code">arg0</span>, <span class="name">eventID</span></div> <div class="text">The unique ID for this mutex lock acquisition.</div> </li> <li> <div><span class="code">arg1</span>, <span class="name">regexUTF8</span></div> <div class="text">Up to 64 characters of the regular expression encoded in <span class="hardNobr code">UTF-8</span>. Must be copied with <span class="hardNobr code">copyinstr(arg1)</span>.</div> </li> <li> <div><span class="code">arg2</span>, <span class="name">options</span></div> <div class="text">The <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> options used.</div> </li> <li> <div><span class="code">arg3</span>, <span class="name">captures</span></div> <div class="text">The number of captures present in the regular expression, or <span class="code">-1</span> if there was an error.</div> </li> <li> <div><span class="code">arg4</span>, <span class="name">hitMiss</span></div> <div class="text">A boolean value that indicates whether or not this event was a cache hit or not, or <span class="code">-1</span> if there was an error.</div> </li> <li> <div><span class="code">arg5</span>, <span class="name">icuStatusCode</span></div> <div class="text">If an error occurs, this contains the error number returned by ICU.</div> </li> <li> <div><span class="code">arg6</span>, <span class="name">icuErrorMessage</span></div> <div class="text">If an error occurs, this contains a <span class="hardNobr code">UTF-8</span> encoded string of the ICU error. Must be copied with <span class="hardNobr code">copyinstr(arg6)</span>.</div> </li> <li> <div><span class="code">arg7</span>, <span class="name">hitRate</span></div> <div class="text">A pointer to a floating point value, between <span class="hardNobr code">0.0</span> and <span class="hardNobr code">100.0</span>, that represents the effectiveness of cache. Higher is better. Must be copied with <span class="hardNobr code">copyin(arg7, sizeof(double))</span>.</div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>An example of how to copy the <span class="code">double</span> value pointed to by <span class="argument">hitRate</span>:</p> <div class="box sourcecode">RegexKitLite*:::compiledRegexCache { this-&gt;hitRate = (double *)copyin(arg7, sizeof(double)); printf(&quot;compiledRegexCache hitRate: %6.2f%%\n&quot;, this-&gt;hitRate); }</div> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#DTrace_RegexKitLiteProbePoints__utf16ConversionCache" class="code">RegexKitLite:::utf16ConversionCache</a></li> <li><a href="#UsingRegexKitLite_DTrace" class="section-link">Using <span class="rkl">RegexKit<i>Lite</i></span> - DTrace</a></li> <li><a href="http://docs.sun.com/app/docs/doc/817-6223" class="section-link printURL">Solaris Dynamic Tracing Guide</a> <a href="http://dlc.sun.com/pdf/817-6223/817-6223.pdf" class="section-link printURL">(as .PDF)</a></li> </ul> </div> </div> <div class="block dtrace"> <div class="section name softNobr" id="DTrace_RegexKitLiteProbePoints__utf16ConversionCache">RegexKitLite:::utf16ConversionCache</div> <div class="section summary">This probe point fires each time the <span class="hardNobr code">UTF-16</span> conversion cache is accessed.</div> <div class="signature"><span class="hardNobr"><span class="function">RegexKitLite:::utf16ConversionCache</span>(</span><span class="hardNobr">unsigned long <span class="argument">eventID</span>,</span> <span class="hardNobr">unsigned int <span class="argument">lookupResultFlags</span>,</span> <span class="hardNobr">double *<span class="argument">hitRate</span>,</span> <span class="hardNobr">const void *<span class="argument">string</span>,</span> <span class="hardNobr">unsigned long <span class="argument">NSRange_location</span>,</span> <span class="hardNobr">unsigned long <span class="argument">NSRange_length</span>,</span> <span class="hardNobr">long <span class="argument">length</span>);</span></div> <div class="section parameters"><div class="header">Arguments</div> <ul> <li> <div><span class="code">arg0</span>, <span class="name">eventID</span></div> <div class="text">The unique ID for this mutex lock acquisition.</div> </li> <li> <div><span class="code">arg1</span>, <span class="name">lookupResultFlags</span></div> <div class="text">A set of status flags about the result of the conversion cache lookup.</div> </li> <li> <div><span class="code">arg2</span>, <span class="name">hitRate</span></div> <div class="text">A pointer to a floating point value, between <span class="hardNobr code">0.0</span> and <span class="hardNobr code">100.0</span>, that represents the effectiveness of cache. Higher is better. Must be copied with <span class="hardNobr code">copyin(arg2, sizeof(double))</span>.</div> </li> <li> <div><span class="code">arg3</span>, <span class="name">string</span></div> <div class="text">A pointer to the <span class="code">NSString</span> that this <span class="code">UTF-16</span> conversion cache check is being performed on.</div> </li> <li> <div><span class="code">arg4</span>, <span class="name">NSRange_location</span></div> <div class="text">The location value of the <span class="argument">range</span> argument from the invoking <span class="rkl">RegexKit<i>Lite</i></span> method.</div> </li> <li> <div><span class="code">arg5</span>, <span class="name">NSRange_length</span></div> <div class="text">The length value of the <span class="argument">range</span> argument from the invoking <span class="rkl">RegexKit<i>Lite</i></span> method.</div> </li> <li> <div><span class="code">arg6</span>, <span class="name">length</span></div> <div class="text">The length of the string.</div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>Only strings that require a <span class="code">UTF-16</span> conversion count towards the value calculated for <span class="argument">hitRate</span>.</p> <p>An example of how to copy the <span class="code">double</span> value pointed to by <span class="argument">hitRate</span>:</p> <div class="box sourcecode">RegexKitLite*:::utf16ConversionCache { this-&gt;hitRate = (double *)copyin(arg2, sizeof(double)); printf(&quot;utf16ConversionCache hitRate: %6.2f%%\n&quot;, this-&gt;hitRate); }</div> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#DTrace_RegexKitLiteProbePoints__compiledRegexCache" class="code">RegexKitLite:::compiledRegexCache</a></li> <li><a href="#dtrace_utf16ConversionCache_lookupResultFlags" class="section-link">RegexKitLite:::utf16ConversionCache arg1 Flags</a></li> <li><a href="#UsingRegexKitLite_DTrace" class="section-link">Using <span class="rkl">RegexKit<i>Lite</i></span> - DTrace</a></li> <li><a href="http://docs.sun.com/app/docs/doc/817-6223" class="section-link printURL">Solaris Dynamic Tracing Guide</a> <a href="http://dlc.sun.com/pdf/817-6223/817-6223.pdf" class="section-link printURL">(as .PDF)</a></li> </ul> </div> </div> <h2>Class Methods</h2> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__.captureCountForRegex:">captureCountForRegex:</div> <div class="section summary">Returns the number of captures that <span class="argument">regex</span> contains. <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0.</span> Use <a href="#NSString_RegexKitLiteAdditions__-captureCount" class="code">captureCount</a> instead.</div> <div class="signature"><span class="hardNobr">+ (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">captureCountForRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>Since the capture count of a regular expression does not depend on the string to be searched, this is a <span class="code">NSString</span> class method. For example:</p> <div class="box sourcecode">NSInteger regexCaptureCount = [NSString captureCountForRegex:@&quot;(\\d+)\.(\\d+)&quot;]; // <span class="comment">regexCaptureCount would be set to 2.</span></div> </div> <div class="section availability"><div class="header">Availability</div><p>Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</p></div> <div class="section result"><div class="header">Return Value</div> <p>Returns <span class="code hardNobr">-1</span> if an error occurs. Otherwise the number of captures in <span class="argument">regex</span> is returned, or <span class="code">0</span> if <span class="argument">regex</span> does not contain any captures.</p> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__.captureCountForRegex:options:error:" class="code">+ captureCountForRegex:options:error:</a> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCount" class="code">- captureCount</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:" class="code">- captureCountWithOptions:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__.captureCountForRegex:options:error:">captureCountForRegex:options:error:</div> <div class="section summary">Returns the number of captures that <span class="argument">regex</span> contains. <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0.</span> Use <a href="#NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:" class="code">captureCountWithOptions:error:</a> instead.</div> <div class="signature"><span class="hardNobr">+ (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">captureCountForRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>The optional <span class="argument">error</span> parameter, if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</p> <p>Since the capture count of a regular expression does not depend on the string to be searched, this is a <span class="code">NSString</span> class method. For example:</p> <div class="box sourcecode">NSInteger regexCaptureCount = [NSString captureCountForRegex:@&quot;(\\d+)\.(\\d+)&quot; options:RKLNoOptions error:NULL]; // <span class="comment">regexCaptureCount would be set to 2.</span></div> </div> <div class="section availability"><div class="header">Availability</div> <p>Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</p> </div> <div class="section result"><div class="header">Return Value</div> <p>Returns <span class="code hardNobr">-1</span> if an error occurs. Otherwise the number of captures in <span class="argument">regex</span> is returned, or <span class="code">0</span> if <span class="argument">regex</span> does not contain any captures.</p> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__.captureCountForRegex:" class="code">+ captureCountForRegex:</a> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCount" class="code">- captureCount</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:" class="code">- captureCountWithOptions:error:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__.clearStringCache">clearStringCache</div> <div class="section summary">Clears the cached information about strings and cached compiled regular expressions.</div> <div class="signature"><span class="hardNobr">+ (void)<span class="selector">clearStringCache</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>This method clears all the the cached state maintained by <span class="rkl">RegexKit<i>Lite</i></span>. This includes all the cached compiled regular expressions and any cached <span class="code">UTF-16</span> conversions.</p> <p>An example of clearing the cache:</p> <div class="box sourcecode">[NSString clearStringCache]; // <span class="comment">Clears all RegexKitLite cache state.</span></div> <div class="box warning"><div class="table"><div class="row"><div class="label cell">Warning:</div><div class="message cell"> <p>When searching <span class="code">NSMutableString</span> objects that have mutated between searches, failure to clear the cache may result in undefined behavior. Use <a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">flushCachedRegexData</a> to selectively clear the cached information about a <span class="code">NSMutableString</span> object.</p> </div></div></div></div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>You do not need to call <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">clearStringCache</a> or <a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">flushCachedRegexData</a> when using the <span class="code">NSMutableString</span> <a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">replaceOccurrencesOfRegex:withString:</a> methods. The cache entry for that regular expression and <span class="code">NSMutableString</span> is automatically cleared as necessary.</p> </div></div></div></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.1 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">- flushCachedRegexData</a></li> <li><a href="#NSString_RegexKitLiteAdditions__CachedInformationandMutableStrings" class="section-link">NSString <span class="rkl">RegexKit<i>Lite</i></span> Additions Reference - Cached Information and Mutable Strings</a></li> </ul> </div> </div> <h2 class="InstanceMethods">Instance Methods</h2> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:">arrayOfCaptureComponentsMatchedByRegex:</div> <div class="section summary">Returns an array containing all the matches from the receiver that were matched by the regular expression <span class="argument">regex</span>. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfCaptureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSArray</span> which contains all the capture groups present in <span class="argument">regex</span>. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</p></div> <div class="section discussion"><div class="header">Discussion</div><p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:range:" class="code">- arrayOfCaptureComponentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:options:range:error:" class="code">- arrayOfCaptureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:range:">arrayOfCaptureComponentsMatchedByRegex:range:</div> <div class="section summary">Returns an array containing all the matches from the receiver that were matched by the regular expression <span class="argument">regex</span> within <span class="argument">range</span>. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfCaptureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSArray</span> which contains all the capture groups present in <span class="argument">regex</span>. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</p></div> <div class="section discussion"><div class="header">Discussion</div><p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:" class="code">- arrayOfCaptureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:options:range:error:" class="code">- arrayOfCaptureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:options:range:error:">arrayOfCaptureComponentsMatchedByRegex:options:range:error:</div> <div class="section summary">Returns an array containing all the matches from the receiver that were matched by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span>. Each match result consists of an array of the substrings matched by all the capture groups present in the regular expression.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfCaptureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSArray</span> which contains all the capture groups present in <span class="argument">regex</span>. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</p></div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p> <p>The match results in the array appear in the order they did in the receiver. For example, this code fragment:</p> <div class="box sourcecode">NSString *list = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSArray <span class="hardNobr">*listItems = [list</span> arrayOfCaptureComponentsMatchedByRegex:<span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;];</span></div> <p style="margin-top: 0.75em">produces a <span class="code">NSArray</span> equivalent to:</p> <div class="box sourcecode">[NSArray arrayWithObjects: [NSArray arrayWithObjects: <span class="hardNobr">@&quot;$10.23&quot;,</span> <span class="hardNobr">@&quot;10.23&quot;,</span> <span class="hardNobr">@&quot;10&quot;,</span> <span class="hardNobr">@&quot;23&quot;,</span> <span class="hardNobr">NULL],</span> <span class="hardNobr">// <span class="comment">Index 0</span></span> [NSArray arrayWithObjects:<span class="hardNobr">@&quot;$1024.42&quot;,</span> <span class="hardNobr">@&quot;1024.42&quot;,</span> <span class="hardNobr">@&quot;1024&quot;,</span> <span class="hardNobr">@&quot;42&quot;,</span> <span class="hardNobr">NULL],</span> <span class="hardNobr">// <span class="comment">Index 1</span></span> [NSArray arrayWithObjects: <span class="hardNobr">@&quot;$3099&quot;,</span> <span class="hardNobr">@&quot;3099&quot;,</span> <span class="hardNobr">@&quot;3099&quot;,</span> <span class="hardNobr">@&quot;&quot;,</span> <span class="hardNobr">NULL],</span> <span class="hardNobr">// <span class="comment">Index 2</span></span> NULL];</div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:" class="code">- arrayOfCaptureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:range:" class="code">- arrayOfCaptureComponentsMatchedByRegex:range:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:">arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:</div> <div class="section summary">Returns an array containing all the matches in the receiver that were matched by the regular expression <span class="argument">regex</span>. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfDictionariesByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSDictionary</span> containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:">arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:</div> <div class="section summary">Returns an array containing all the matches in the receiver that were matched by the regular expression <span class="argument">regex</span> within <span class="argument">range</span>. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfDictionariesByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSDictionary</span> containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:">arrayOfDictionariesByMatchingRegex:options:range:error:withKeysAndCaptures:</div> <div class="section summary">Returns an array containing all the matches in the receiver that were matched by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span>. Each match result consists of a dictionary containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">arrayOfDictionariesByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the matches from the receiver by <span class="argument">regex</span>. Each match result consists of a <span class="code">NSDictionary</span> containing that matches substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text. It is important to note that a regular expression can successfully match zero characters:</p> <div class="box sourcecode"> NSString *name = @&quot;Name: Bob\n&quot; @&quot;Name: John Smith&quot;; NSString *regex = @&quot;(?m)^Name:\\s*(\\w*)\\s*(\\w*)$&quot;; NSArray *nameArray = [name arrayOfDictionariesByMatchingRegex:regex options:RKLNoOptions range:NSMakeRange(0UL,) error:NULL withKeysAndCaptures:@&quot;first&quot;, 1, @&quot;last&quot;, 2, NULL]; // <span class="comment">2010-04-16 01:15:30.061 RegexKitLite[42984:a0f] nameArray: (</span> // <span class="comment">{ first = Bob, last = &quot;&quot; },</span> // <span class="comment">{ first = John, last = Smith }</span> // <span class="comment">)</span></div> <p>Compared to this example, where the second capture group does not match any characters:</p> <div class="box sourcecode"> NSString *name = @&quot;Name: Bob\n&quot; @&quot;Name: John Smith&quot;; NSString *regex = @&quot;(?m)^Name:\\s*(\\w*)(?:\\s*|\\s+(\\w+))$&quot;; NSArray *nameArray = [name arrayOfDictionariesByMatchingRegex:regex options:RKLNoOptions range:NSMakeRange(0UL,) error:NULL withKeysAndCaptures:@&quot;first&quot;, 1, @&quot;last&quot;, 2, NULL]; // <span class="comment">2010-04-16 01:15:30.061 RegexKitLite[42984:a0f] nameArray: (</span> // <span class="comment">{ first = Bob },</span> // <span class="comment">{ first = John, last = Smith }</span> // <span class="comment">)</span></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:">captureComponentsMatchedByRegex:</div> <div class="section summary">Returns an array containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> in the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">captureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> in the receiver. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</div> <div class="section discussion"><div class="header">Discussion</div><p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:range:" class="code">- captureComponentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:options:range:error:" class="code">- captureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:range:">captureComponentsMatchedByRegex:range:</div> <div class="section summary">Returns an array containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">captureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</div> <div class="section discussion"><div class="header">Discussion</div><p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:" class="code">- captureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:options:range:error:" class="code">- captureComponentsMatchedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:options:range:error:">captureComponentsMatchedByRegex:options:range:error:</div> <div class="section summary">Returns an array containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver using <span class="argument">options</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">captureComponentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> containing the substrings matched by each capture group present in <span class="argument">regex</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver using <span class="argument">options</span>. Array index <span class="code">0</span> represents all of the text matched by <span class="argument">regex</span> and subsequent array indexes contain the text matched by their respective capture group.</div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>A match result array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p> <p>The returned value is for the first match of <span class="argument">regex</span> in the receiver. For example, this code fragment:</p> <div class="box sourcecode">NSString *list = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSArray <span class="hardNobr">*listItems = [list</span> captureComponentsMatchedByRegex:<span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;];</span></div> <p style="margin-top: 0.75em">produces a <span class="code">NSArray</span> equivalent to:</p> <div class="box sourcecode">[NSArray arrayWithObjects: <span class="hardNobr">@&quot;$10.23&quot;,</span> <span class="hardNobr">@&quot;10.23&quot;,</span> <span class="hardNobr">@&quot;10&quot;,</span> <span class="hardNobr">@&quot;23&quot;,</span> <span class="hardNobr">NULL];</span></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:" class="code">- captureComponentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:range:" class="code">- captureComponentsMatchedByRegex:range:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-captureCount">captureCount</div> <div class="section summary">Returns the number of captures that <span class="argument">regex</span> contains.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">captureCount</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>Returns the capture count of the receiver, which should be a valid regular expression. For example:</p> <div class="box sourcecode">NSInteger regexCaptureCount = [@&quot;(\\d+)\.(\\d+)&quot; captureCount]; // <span class="comment">regexCaptureCount would be set to 2.</span></div> </div> <div class="section result"><div class="header">Return Value</div> <p>Returns <span class="code hardNobr">-1</span> if an error occurs. Otherwise the number of captures in <span class="argument">regex</span> is returned, or <span class="code">0</span> if <span class="argument">regex</span> does not contain any captures.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:" class="code">- captureCountWithOptions:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-captureCountWithOptions:error:">captureCountWithOptions:error:</div> <div class="section summary">Returns the number of captures that <span class="argument">regex</span> contains.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">captureCountWithOptions:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>The optional <span class="argument">error</span> parameter, if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</p> <p>Returns the capture count of the receiver, which should be a valid regular expression. For example:</p> <div class="box sourcecode">NSInteger regexCaptureCount = [@&quot;(\\d+)\.(\\d+)&quot; captureCountWithOptions:RKLNoOptions error:NULL]; // <span class="comment">regexCaptureCount would be set to 2.</span></div> </div> <div class="section result"><div class="header">Return Value</div> <p>Returns <span class="code hardNobr">-1</span> if an error occurs. Otherwise the number of captures in <span class="argument">regex</span> is returned, or <span class="code">0</span> if <span class="argument">regex</span> does not contain any captures.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-captureCount" class="code">- captureCount</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:">componentsMatchedByRegex:</div> <div class="section summary">Returns an array containing all the substrings from the receiver that were matched by the regular expression <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the substrings from the receiver that were matched by <span class="argument">regex</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:capture:" class="code">- componentsMatchedByRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:range:" class="code">- componentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:options:range:capture:error:" class="code">- componentsMatchedByRegex:options:range:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:capture:">componentsMatchedByRegex:capture:</div> <div class="section summary">Returns an array containing all the substrings from the receiver that were matched by capture number <span class="argument">capture</span> from the regular expression <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the substrings for capture group <span class="argument">capture</span> from the receiver that were matched by <span class="argument">regex</span>.</div> <div class="section discussion"><div class="header">Discussion</div><p>An array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if the capture group did not match any text.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">- componentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:range:" class="code">- componentsMatchedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:options:range:capture:error:" class="code">- componentsMatchedByRegex:options:range:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:range:">componentsMatchedByRegex:range:</div> <div class="section summary">Returns an array containing all the substrings from the receiver that were matched by the regular expression <span class="argument">regex</span> within <span class="argument">range</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the substrings from the receiver that were matched by <span class="argument">regex</span> within <span class="argument">range</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">- componentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:capture:" class="code">- componentsMatchedByRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:options:range:capture:error:" class="code">- componentsMatchedByRegex:options:range:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:options:range:capture:error:">componentsMatchedByRegex:options:range:capture:error:</div> <div class="section summary">Returns an array containing all the substrings from the receiver that were matched by capture number <span class="argument">capture</span> from the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">capture</div> <div class="text">The string matched by <span class="argument">capture</span> from <span class="argument">regex</span> to return. Use <span class="code">0</span> for the entire string that <span class="argument">regex</span> matched.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing all the substrings from the receiver that were matched by capture number <span class="argument">capture</span> from <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSArray</span> that contains no items.</p> <p>An array index will contain an empty string, or <span class="hardNobr code">@&quot;&quot;</span>, if a capture group did not match any text.</p> <p>The match results in the array appear in the order they did in the receiver.</p> <p>Example:</p> <div class="box sourcecode">NSString *list = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSArray <span class="hardNobr">*listItems = [list</span> componentsMatchedByRegex:<span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;</span>]; // <span class="comment">listItems == [NSArray arrayWithObjects:@&quot;$10.23&quot;, @&quot;$1024.42&quot;, @&quot;$3099&quot;, NULL];</span></div> <p style="margin-top: 1em">Example of extracting a specific capture group:</p> <div class="box sourcecode">NSString *list = <span class="hardNobr">@&quot;$10.23, $1024.42, $3099&quot;;</span> NSRange listRange = <span class="hardNobr">NSMakeRange(0UL,</span> <span class="hardNobr">[list length]);</span> NSArray <span class="hardNobr">*listItems = [list</span> componentsMatchedByRegex:<span class="hardNobr">@&quot;\\$((\\d+)(?:\\.(\\d+)|\\.?))&quot;</span> <span class="hardNobr">options:RKLNoOptions</span> <span class="hardNobr">range:listRange</span> <span class="hardNobr">capture:3L</span> <span class="hardNobr">error:NULL];</span> // <span class="comment">listItems == [NSArray arrayWithObjects:@&quot;23&quot;, @&quot;42&quot;, @&quot;&quot;, NULL];</span></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">- componentsMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:capture:" class="code">- componentsMatchedByRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:range:" class="code">- componentsMatchedByRegex:range:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:">componentsSeparatedByRegex:</div> <div class="section summary">Returns an array containing substrings from the receiver that have been divided by the regular expression <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing the substrings from the receiver that have been divided by <span class="argument">regex</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:range:" class="code">- componentsSeparatedByRegex:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:options:range:error:" class="code">- componentsSeparatedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:range:">componentsSeparatedByRegex:range:</div> <div class="section summary">Returns an array containing substrings within <span class="argument">range</span> of the receiver that have been divided by the regular expression <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing the substrings from the receiver that have been divided by <span class="argument">regex</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">- componentsSeparatedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:options:range:error:" class="code">- componentsSeparatedByRegex:options:range:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:options:range:error:">componentsSeparatedByRegex:options:range:error:</div> <div class="section summary">Returns an array containing substrings within <span class="argument">range</span> of the receiver that have been divided by the regular expression <span class="argument">regex</span> using <span class="argument">options</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSArray</span> object containing the substrings from the receiver that have been divided by <span class="argument">regex</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>The substrings in the array appear in the order they did in the receiver. For example, this code fragment:</p> <div class="box sourcecode">NSString *list = @&quot;Norman, Stanley, Fletcher&quot;; NSArray *listItems = [list componentsSeparatedByRegex:@&quot;,\\s*&quot;];</div> <p>produces an array <span class="code">{ @&quot;Norman&quot;, @&quot;Stanley&quot;, @&quot;Fletcher&quot; }</span>.</p> <p>If the receiver begins or ends with <span class="argument">regex</span>, then the first or last substring is, respectively, empty. For example, the <span class="hardNobr">string <span class="code">&quot;, Norman, Stanley, Fletcher&quot;</span></span> creates an array that has these <span class="hardNobr">contents: <span class="code">{ @&quot;&quot;, @&quot;Norman&quot;, @&quot;Stanley&quot;, @&quot;Fletcher&quot; }</span>.</span></p> <p>If the receiver has no separators that are matched by <span class="argument">regex</span>&mdash;for example, <span class="code">&quot;Norman&quot;</span>&mdash;the array contains the string itself, in this <span class="hardNobr">case <span class="code">{ @&quot;Norman&quot; }</span>.</span></p> <p>If <span class="argument">regex</span> contains capture groups&mdash;for example, <span class="code hardNobr">@&quot;,(\\s*)&quot;</span>&mdash;the array will contain the text matched by each capture group as a separate element appended to the normal result. An additional element will be created for each capture group. If an individual capture group does not match any text the result in the array will be a zero length string&mdash;<span class="code">@&quot;&quot;</span>. As an example&mdash;the regular expression <span class="code hardNobr">@&quot;,(\\s*)&quot;</span> would produce the <span class="hardNobr">array <span class="code">{ @&quot;Norman&quot;, @&quot; &quot;, @&quot;Stanley&quot;, @&quot; &quot;, @&quot;Fletcher&quot; }</span>.</span></p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">- componentsSeparatedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:range:" class="code">- componentsSeparatedByRegex:range:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:withKeysAndCaptures:">dictionaryByMatchingRegex:withKeysAndCaptures:</div> <div class="section summary">Creates and returns a dictionary containing the matches constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span> for the first match of <span class="argument">regex</span> in the receiver.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html">NSDictionary</a> *)<span class="selector">dictionaryByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSDictionary</span> containing the matched substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>The returned value is for the first match of <span class="argument">regex</span> in the receiver.</p> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSDictionary</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:range:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:range:withKeysAndCaptures:">dictionaryByMatchingRegex:range:withKeysAndCaptures:</div> <div class="section summary">Creates and returns a dictionary containing the matches constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html">NSDictionary</a> *)<span class="selector">dictionaryByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSDictionary</span> containing the matched substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>The returned value is for the first match of <span class="argument">regex</span> in the receiver.</p> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSDictionary</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:">dictionaryByMatchingRegex:options:range:error:withKeysAndCaptures:</div> <div class="section summary">Creates and returns a dictionary containing the matches constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver using <span class="argument">options</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html">NSDictionary</a> *)<span class="selector">dictionaryByMatchingRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">withKeysAndCaptures:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/id">id</a>)<span class="argument">firstKey</span>, <span class="argument">...</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">firstKey</div> <div class="text">The first key to add to the new dictionary.</div> </li> <li> <div class="name">...</div> <div class="text">First the <span class="argument">capture</span> for <span class="argument">firstKey</span>, then a <span class="code">NULL</span>-terminated list of alternating <span class="argument">keys</span> and <span class="argument">captures</span>. <span class="argument">Captures</span> are specified using <span class="code">int</span> values. <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Use of non-<span class="code">int</span> sized <span class="argument">capture</span> arguments will result in undefined behavior. <b>Do not</b> append <span class="argument">capture</span> arguments with a <span class="code">L</span> suffix.</p> </div></div></div></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> <p>Failure to <span class="code">NULL</span>-terminate the <span class="argument">keys</span> and <span class="argument">captures</span> list will result in undefined behavior.</p> </div></div></div></div></div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>A <span class="code">NSDictionary</span> containing the matched substrings constructed from the specified set of <span class="argument">keys</span> and <span class="argument">captures</span>.</div> <div class="section discussion"><div class="header">Discussion</div> <p>The returned value is for the first match of <span class="argument">regex</span> in the receiver.</p> <p>If the receiver is not matched by <span class="argument">regex</span> then the returned value is a <span class="code">NSDictionary</span> that contains no items.</p> <p>A dictionary will not contain a given key if its corresponding capture group did not match any text. It is important to note that a regular expression can successfully match zero characters:</p> <div class="box sourcecode">NSString *name = @&quot;Name: Joe&quot;; NSString *regex = @&quot;Name:\\s*(\\w*)\\s*(\\w*)&quot;; NSDictionary *nameDictionary = [name dictionaryByMatchingRegex:regex options:RKLNoOptions range:NSMakeRange(0UL,) error:NULL withKeysAndCaptures:@&quot;first&quot;, 1, @&quot;last&quot;, 2, NULL]; // <span class="comment">2010-01-29 12:19:54.559 RegexKitLite[64944:a0f] nameDictionary: {</span> // <span class="comment">first = Joe;</span> // <span class="comment">last = &quot;&quot;;</span> // <span class="comment">}</span></div> <p>Compared to this example, where the second capture group does not match any characters:</p> <div class="box sourcecode">NSString *name = @&quot;Name: Joe&quot;; NSString *regex = @&quot;Name:\\s*(\\w*)\\s*(\\w<span class="highlight">+)?</span>&quot;; NSDictionary *nameDictionary = [name dictionaryByMatchingRegex:regex options:RKLNoOptions range:NSMakeRange(0UL, [name length]) error:NULL withKeysAndCaptures:@&quot;first&quot;, 1, @&quot;last&quot;, 2, NULL]; // <span class="comment">2010-01-29 12:12:52.177 RegexKitLite[64893:a0f] nameDictionary: {</span> // <span class="comment">first = Joe;</span> // <span class="comment">}</span></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:range:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:range:withKeysAndCaptures:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:usingBlock:">enumerateStringsMatchedByRegex:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> and executes <span class="argument">block</span> for each match found.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">enumerateStringsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span>(void (^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">YES</span> if there was no error, otherwise returns <span class="code">NO</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:" class="code">- enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:">enumerateStringsMatchedByRegex:options:inRange:error:enumerationOptions:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span> and executes <span class="argument">block</span> using <span class="argument">enumerationOptions</span> for each match found.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">enumerateStringsMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span>(void (^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="code">NSError</a> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">enumerationOptions</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions" class="code">RKLRegexEnumerationNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">YES</span> if there was no error, otherwise returns <span class="code">NO</span> and indirectly returns a <span class="code">NSError</span> object if <span class="argument">error</span> is not <span class="code">NULL</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:usingBlock:" class="code">- enumerateStringsMatchedByRegex:usingBlock:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:usingBlock:">enumerateStringsSeparatedByRegex:usingBlock:</div> <div class="section summary">Enumerates the strings of the receiver that have been divided by the regular expression <span class="argument">regex</span> and executes <span class="argument">block</span> for each divided string.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">enumerateStringsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span>(void (^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">YES</span> if there was no error, otherwise returns <span class="code">NO</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:" class="code">- enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">- componentsSeparatedByRegex:</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:">enumerateStringsSeparatedByRegex:options:inRange:error:enumerationOptions:usingBlock:</div> <div class="section summary">Enumerates the strings of the receiver that have been divided by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span> and executes <span class="argument">block</span> using <span class="argument">enumerationOptions</span> for each divided string.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">enumerateStringsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span>(void (^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="code">NSError</a> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">enumerationOptions</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions" class="code">RKLRegexEnumerationNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">YES</span> if there was no error, otherwise returns <span class="code">NO</span> and indirectly returns a <span class="code">NSError</span> object if <span class="argument">error</span> is not <span class="code">NULL</span>.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:usingBlock:" class="code">- enumerateStringsSeparatedByRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:options:range:error:" class="code">- componentsSeparatedByRegex:options:range:error:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-flushCachedRegexData">flushCachedRegexData</div> <div class="section summary">Clears any cached information about the receiver.</div> <div class="signature"><span class="hardNobr">- (void)<span class="selector">flushCachedRegexData</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>This method should be used when performing searches on <span class="code">NSMutableString</span> objects and there is the possibility that the string has mutated in between calls to <span class="rkl">RegexKit<i>Lite</i></span>.</p> <p>This method clears the cached information for the receiver <b>only</b>. This is more selective than <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">clearStringCache</a>, which clears all the cached information from <span class="rkl">RegexKit<i>Lite</i></span>, including all the cached compiled regular expressions.</p> <p><span class="rkl">RegexKit<i>Lite</i></span> automatically detects the vast majority of string mutations and clears any cached information for the mutated string. To detect mutations, <span class="rkl">RegexKit<i>Lite</i></span> records a strings <span class="code">length</span> and <span class="code">hash</span> value at the point in time when it caches data for a string. Cached data for a string is invalidated if either of these values change between calls to <span class="rkl">RegexKit<i>Lite</i></span>. The problem case is when a string is mutated but the strings length remains the same <b>and</b> the hash value for the mutated string is identical to the hash value of the string before it was mutated. This is known as a <i>hash collision</i>. Since <span class="rkl">RegexKit<i>Lite</i></span> is unable to detect that a string has mutated when this happens, the programmer needs to explicitly inform <span class="rkl">RegexKit<i>Lite</i></span> that any cached data about the receiver needs to be cleared by sending <span class="code">flushCachedRegexData</span> to the mutated string.</p> <p>While it is possible to have &quot;perfect mutation detection&quot;, and therefore guarantee that only valid cached data is used, it has a significant performance penalty. The first problem is that when caching information about a string, an immutable copy of that string needs to be made. The second problem is that determining that two strings are not identical is usually very fast and cheap&mdash; if their lengths are not the same, no further checks are required. The most expensive case is when two strings are identical because it requires a character by character comparison of the entire string to guarantee that they are equal. The most expensive case also happens to be the most common case, by far. To make matters worst, Cocoa provides no public way to determine if an instance is a mutable <span class="code">NSMutableString</span> or an immutable <span class="code">NSString</span> object. Therefore <span class="rkl">RegexKit<i>Lite</i></span> must assume the worst case that all strings are mutable and have potentially mutated between calls to <span class="rkl">RegexKit<i>Lite</i></span>.</p> <p><span class="rkl">RegexKit<i>Lite</i></span> is optimized for the common case which is when regular expression operations are performed on strings that are not mutating. The majority of mutations to a string can be quickly and cheaply detected by <span class="rkl">RegexKit<i>Lite</i></span> automatically. Since the programmer has the context of the string that is to be matched, and whether or not the string is being mutated, <span class="rkl">RegexKit<i>Lite</i></span> relies on the programmer to inform it whether or not the possibility exists that the string could have mutated in a way that is undetectable.</p> <p>An example of clearing a strings cached information:</p> <div class="box sourcecode">NSMutableString *mutableSearchString; // <span class="comment">Assumed to be valid.</span> NSString *foundString = [mutableSearchString stringByMatching:@&quot;\\d+&quot;]; // <span class="comment">Searched..</span> [mutableSearchString replaceCharactersInRange:NSMakeRange(5UL, 10UL) withString:@&quot;[replaced]&quot;]; // <span class="comment">Mutated..</span> [mutableSearchString flushCachedRegexData]; // <span class="comment">Clear cached information about mutableSearchString.</span></div> <div class="box warning"><div class="table"><div class="row"><div class="label cell">Warning:</div><div class="message cell"> <p>Failure to clear the cached information for a <span class="code">NSMutableString</span> object that has mutated between searches may result in undefined behavior.</p> </div></div></div></div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>You do not need to call <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">clearStringCache</a> or <a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="code">flushCachedRegexData</a> when using the <span class="code">NSMutableString</span> <a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">replaceOccurrencesOfRegex:withString:</a> methods. The cached information for that <span class="code">NSMutableString</span> is automatically cleared as necessary.</p> </div></div></div></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__.clearStringCache" class="code">+ clearStringCache</a></li> <li><a href="#NSString_RegexKitLiteAdditions__CachedInformationandMutableStrings" class="section-link">NSString <span class="rkl">RegexKit<i>Lite</i></span> Additions Reference - Cached Information and Mutable Strings</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-isMatchedByRegex:">isMatchedByRegex:</div> <div class="section summary">Returns a Boolean value that indicates whether the receiver is matched by <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">isMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:inRange:" class="code">- isMatchedByRegex:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:options:inRange:error:" class="code">- isMatchedByRegex:options:inRange:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-isMatchedByRegex:inRange:">isMatchedByRegex:inRange:</div> <div class="section summary">Returns a Boolean value that indicates whether the receiver is matched by <span class="argument">regex</span> within <span class="argument">range</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">isMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span>;</span></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:" class="code">- isMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:options:inRange:error:" class="code">- isMatchedByRegex:options:inRange:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-isMatchedByRegex:options:inRange:error:">isMatchedByRegex:options:inRange:error:</div> <div class="section summary">Returns a Boolean value that indicates whether the receiver is matched by <span class="argument">regex</span> within <span class="argument">range</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">isMatchedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section discussion"><div class="header">Discussion</div> <p>The optional <span class="argument">error</span> parameter, if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:" class="code">- isMatchedByRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-isMatchedByRegex:inRange:" class="code">- isMatchedByRegex:inRange:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-isRegexValid">isRegexValid</div> <div class="section summary">Returns a Boolean value that indicates whether the regular expression contained in the receiver is valid.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">isRegexValid</span>;</span></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isRegexValidWithOptions:error:" class="code">- isRegexValidWithOptions:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-isRegexValidWithOptions:error:">isRegexValidWithOptions:error:</div> <div class="section summary">Returns a Boolean value that indicates whether the regular expression contained in the receiver is valid using <span class="argument">options</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<span class="selector">isRegexValidWithOptions:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>This method can be used to determine if a regular expression is valid. For example:</p> <div class="box sourcecode">NSError *error = NULL; NSString *regexString = @&quot;[a-z&quot;; // <span class="comment">Missing the closing ]</span> if([regexString isRegexValidWithOptions:RKLNoOptions error:&amp;error] == NO) { NSLog(@&quot;The regular expression is invalid. Error: %@&quot;, error); }</div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-isRegexValid" class="code">- isRegexValid</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-rangeOfRegex:">rangeOfRegex:</div> <div class="section summary">Returns the range for the first match of <span class="argument">regex</span> in the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="selector">rangeOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSRange</span> structure giving the location and length of the first match of <span class="argument">regex</span> in the receiver. Returns <span class="hardNobr"><span class="code">{</span><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSNotFound" class="code">NSNotFound</a><span class="code">, 0}</span></span> if the receiver is not matched by <span class="argument">regex</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:capture:" class="code">- rangeOfRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:inRange:" class="code">- rangeOfRegex:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:" class="code">- rangeOfRegex:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-rangeOfRegex:capture:">rangeOfRegex:capture:</div> <div class="section summary">Returns the range of capture number <span class="argument">capture</span> for the first match of <span class="argument">regex</span> in the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="selector">rangeOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSRange</span> structure giving the location and length of capture number <span class="argument">capture</span> for the first match of <span class="argument">regex</span> in the receiver. Returns <span class="hardNobr"><span class="code">{</span><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSNotFound" class="code">NSNotFound</a><span class="code">, 0}</span></span> if the receiver is not matched by <span class="argument">regex</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:" class="code">- rangeOfRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:inRange:" class="code">- rangeOfRegex:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:" class="code">- rangeOfRegex:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-rangeOfRegex:inRange:">rangeOfRegex:inRange:</div> <div class="section summary">Returns the range for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="selector">rangeOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSRange</span> structure giving the location and length of the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver. Returns <span class="hardNobr"><span class="code">{</span><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSNotFound" class="code">NSNotFound</a><span class="code">, 0}</span></span> if the receiver is not matched by <span class="argument">regex</span> within <span class="argument">range</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:" class="code">- rangeOfRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:capture:" class="code">- rangeOfRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:" class="code">- rangeOfRegex:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-rangeOfRegex:options:inRange:capture:error:">rangeOfRegex:options:inRange:capture:error:</div> <div class="section summary">Returns the range of capture number <span class="argument">capture</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="selector">rangeOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">capture</div> <div class="text">The matching range of the capture number from <span class="argument">regex</span> to return. Use <span class="code">0</span> for the entire range that <span class="argument">regex</span> matched.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSRange</span> structure giving the location and length of capture number <span class="argument">capture</span> for the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver. Returns <span class="hardNobr"><span class="code">{</span><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSNotFound" class="code">NSNotFound</a><span class="code">, 0}</span></span> if the receiver is not matched by <span class="argument">regex</span> within <span class="argument">range</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:" class="code">- rangeOfRegex:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:capture:" class="code">- rangeOfRegex:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-rangeOfRegex:inRange:" class="code">- rangeOfRegex:inRange:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:">replaceOccurrencesOfRegex:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> and executes <span class="argument">block</span> for each match found. Replaces the characters that were matched with the contents of the string returned by <span class="argument">block</span>, returning the number of replacements made.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *(^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>This method modifies the receivers contents. An exception will be raised if it is sent to an immutable object.</p> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">-1</span> if there was an error, otherwise returns the number of replacements performed.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:" class="code">- replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:">replaceOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span> and executes <span class="argument">block</span> using <span class="argument">enumerationOptions</span> for each match found. Replaces the characters that were matched with the contents of the string returned by <span class="argument">block</span>, returning the number of replacements made.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *(^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="code">NSError</a> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">enumerationOptions</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions" class="code">RKLRegexEnumerationNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>This method modifies the receivers contents. An exception will be raised if it is sent to an immutable object.</p> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">-1</span> if there was an error and indirectly returns a <span class="code">NSError</span> object if <span class="argument">error</span> is not <span class="code">NULL</span>, otherwise returns the number of replacements performed.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:" class="code">- replaceOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:">replaceOccurrencesOfRegex:withString:</div> <div class="section summary">Replaces all occurrences of the regular expression <span class="argument">regex</span> with the contents of <span class="argument">replacement</span> string after performing capture group substitutions, returning the number of replacements made.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span>;</span></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> <div class="section discussion"><div class="header">Discussion</div> <p>This method modifies the receivers contents. An exception will be raised if it is sent to an immutable object.</p> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">-1</span> if there was an error, otherwise returns the number of replacements performed.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:range:" class="code">- replaceOccurrencesOfRegex:withString:range:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:options:range:error:" class="code">- replaceOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:range:">replaceOccurrencesOfRegex:withString:range:</div> <div class="section summary">Replaces all occurrences of the regular expression <span class="argument">regex</span> within <span class="argument">range</span> with the contents of <span class="argument">replacement</span> string after performing capture group substitutions, returning the number of replacements made.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> <div class="section discussion"><div class="header">Discussion</div> <p>This method modifies the receivers contents. An exception will be raised if it is sent to an immutable object.</p> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">-1</span> if there was an error, otherwise returns the number of replacements performed.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">- replaceOccurrencesOfRegex:withString:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:options:range:error:" class="code">- replaceOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:options:range:error:">replaceOccurrencesOfRegex:withString:options:range:error:</div> <div class="section summary">Replaces all occurrences of the regular expression <span class="argument">regex</span> using <span class="argument">options</span> within <span class="argument">range</span> with the contents of <span class="argument">replacement</span> string after performing capture group substitutions, returning the number of replacements made.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">replacement</div> <div class="text">The string to use as the replacement text for matches by <span class="argument">regex</span>. See <a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a> for more information.</div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section discussion"><div class="header">Discussion</div> <p>This method modifies the receivers contents. An exception will be raised if it is sent to an immutable object.</p> </div> <div class="section result"><div class="header">Return Value</div>Returns <span class="code">-1</span> if there was an error and indirectly returns a <span class="code">NSError</span> object if <span class="argument">error</span> is not <span class="code">NULL</span>, otherwise returns the number of replacements performed.</div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">- replaceOccurrencesOfRegex:withString:</a></li> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:range:" class="code">- replaceOccurrencesOfRegex:withString:range:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByMatching:">stringByMatching:</div> <div class="section summary">Returns a string created from the characters of the receiver that are in the range of the first match of <span class="argument">regex</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByMatching:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSString</span> containing the substring of the receiver matched by <span class="argument">regex</span>. Returns <span class="code">NULL</span> if the receiver is not matched by <span class="argument">regex</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:capture:" class="code">- stringByMatching:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:inRange:" class="code">- stringByMatching:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:options:inRange:capture:error:" class="code">- stringByMatching:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByMatching:capture:">stringByMatching:capture:</div> <div class="section summary">Returns a string created from the characters of the receiver that are in the range of the first match of <span class="argument">regex</span> for <span class="argument">capture</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByMatching:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSString</span> containing the substring of the receiver matched by capture number <span class="argument">capture</span> of <span class="argument">regex</span>. Returns <span class="code">NULL</span> if the receiver is not matched by <span class="argument">regex</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:" class="code">- stringByMatching:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:inRange:" class="code">- stringByMatching:inRange:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:options:inRange:capture:error:" class="code">- stringByMatching:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByMatching:inRange:">stringByMatching:inRange:</div> <div class="section summary">Returns a string created from the characters of the receiver that are in the range of the first match of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByMatching:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSString</span> containing the substring of the receiver matched by <span class="argument">regex</span> within <span class="argument">range</span> of the receiver. Returns <span class="code">NULL</span> if the receiver is not matched by <span class="argument">regex</span> within <span class="argument">range</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:" class="code">- stringByMatching:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:capture:" class="code">- stringByMatching:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:options:inRange:capture:error:" class="code">- stringByMatching:options:inRange:capture:error:</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByMatching:options:inRange:capture:error:">stringByMatching:options:inRange:capture:error:</div> <div class="section summary">Returns a string created from the characters of the receiver that are in the range of the first match of <span class="argument">regex</span> using <span class="argument">options</span> within <span class="argument">range</span> of the receiver for <span class="argument">capture</span>.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByMatching:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">capture:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<span class="argument">capture</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">capture</div> <div class="text">The string matched by <span class="argument">capture</span> from <span class="argument">regex</span> to return. Use <span class="code">0</span> for the entire string that <span class="argument">regex</span> matched.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div> <p>A <span class="code">NSString</span> containing the substring of the receiver matched by capture number <span class="argument">capture</span> of <span class="argument">regex</span> within <span class="argument">range</span> of the receiver. Returns <span class="code">NULL</span> if the receiver is not matched by <span class="argument">regex</span> within <span class="argument">range</span> or an error occurs.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:" class="code">- stringByMatching:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:capture:" class="code">- stringByMatching:capture:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByMatching:inRange:" class="code">- stringByMatching:inRange:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:">stringByReplacingOccurrencesOfRegex:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> and executes <span class="argument">block</span> for each match found. Returns a string created by replacing the characters that were matched in the receiver with the contents of the string returned by <span class="argument">block</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">usingBlock:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *(^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSString</span> created from the characters of the receiver in which all matches of the regular expression <span class="argument">regex</span> are replaced with the contents of the <span class="code">NSString</span> returned by <span class="argument">block</span>. If the receiver is not matched by <span class="argument">regex</span> then the string that is returned is a copy of the receiver as if <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/stringWithString:" class="code">stringWithString:</a> had been sent to it.</p> <p>Returns <span class="code">NULL</span> if there was an error.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:" class="code">- stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:">stringByReplacingOccurrencesOfRegex:options:inRange:error:enumerationOptions:usingBlock:</div> <div class="section summary">Enumerates the matches in the receiver by the regular expression <span class="argument">regex</span> within <span class="argument">range</span> using <span class="argument">options</span> and executes <span class="argument">block</span> using <span class="argument">enumerationOptions</span> for each match found. Returns a string created by replacing the characters that were matched in the receiver with the contents of the string returned by <span class="argument">block</span>.</div> <div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span> <span class="selector">inRange:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span> <span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span> <span class="selector">enumerationOptions:</span>(<a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a>)<span class="argument">enumerationOptions</span> <span class="selector">usingBlock:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *(^)(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a> <span class="argument">captureCount</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <span class="argument">capturedStrings</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;const <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a> <span class="argument">capturedRanges</span>[captureCount],<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;volatile <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a> * const <span class="argument">stop</span>))<span class="argument">block</span>;</div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html" class="code">NSString</a> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="code">NSError</a> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> <li> <div class="name">enumerationOptions</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions" class="code">RKLRegexEnumerationNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">block</div> <div class="text"> The block that is executed for each match of <span class="argument">regex</span> in the receiver. The block takes four arguments: <div class="section block parameters"> <ul> <li> <div class="name">captureCount</div> <div class="text">The number of strings that <span class="argument">regex</span> captured. <span class="argument">captureCount</span> is always at least <span class="code">1</span>.</div> </li> <li> <div class="name">capturedStrings</div> <div class="text">An array containing the substrings matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a pointer to a string that is equal to <span class="code">@&quot;&quot;</span>. This argument may be <span class="code">NULL</span> if <span class="argument">enumerationOptions</span> had <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> set.</div> </li> <li> <div class="name">capturedRanges</div> <div class="text">An array containing the ranges matched by each capture group present in <span class="argument">regex</span>. The size of the array is <span class="argument">captureCount</span>. If a capture group did not match anything, it will contain a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange" class="code">NSRange</a> equal to <span class="code">{<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/constant_group/NSNotFound">NSNotFound</a>, 0}</span>.</div> </li> <li> <div class="name">stop</div> <div class="text">A reference to a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL" class="code">BOOL</a> value that the block can use to stop the enumeration by setting <span class="hardNobr"><span class="code">*</span><span class="argument">stop</span><span class="code"> = <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/macro/YES">YES</a>;</span>,</span> otherwise it should not touch <span class="code">*</span><span class="argument">stop</span>.</div> </li> </ul> </div> </div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSString</span> created from the characters within <span class="argument">range</span> of the receiver in which all matches of the regular expression <span class="argument">regex</span> using <span class="argument">options</span> are replaced with the contents of the <span class="code">NSString</span> returned by <span class="argument">block</span>. Returns the characters within <span class="argument">range</span> as if <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/substringWithRange:" class="code">substringWithRange:</a> had been sent to the receiver if the substring is not matched by <span class="argument">regex</span>.</p> <p>Returns <span class="code">NULL</span> if there was an error and indirectly returns a <span class="code">NSError</span> object if <span class="argument">error</span> is not <span class="code">NULL</span>.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:" class="code">- stringByReplacingOccurrencesOfRegex:usingBlock:</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> <li><a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a></li> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:">stringByReplacingOccurrencesOfRegex:withString:</div> <div class="section summary">Returns a string created from the characters of the receiver in which all matches of the regular expression <span class="argument">regex</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span>;</span></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSString</span> created from the characters of the receiver in which all matches of the regular expression <span class="argument">regex</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions. If the receiver is not matched by <span class="argument">regex</span> then the string that is returned is a copy of the receiver as if <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/stringWithString:" class="code">stringWithString:</a> had been sent to it.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:range:" class="code">- stringByReplacingOccurrencesOfRegex:withString:range:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:options:range:error:" class="code">- stringByReplacingOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> </ul> </div> </div> <div class="block method"> <div class="section name" id="NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:range:">stringByReplacingOccurrencesOfRegex:withString:range:</div> <div class="section summary">Returns a string created from the characters within <span class="argument">range</span> of the receiver in which all matches of the regular expression <span class="argument">regex</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span>;</span></div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSString</span> created from the characters within <span class="argument">range</span> of the receiver in which all matches of the regular expression <span class="argument">regex</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions. Returns the characters within <span class="argument">range</span> as if <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/substringWithRange:" class="code">substringWithRange:</a> had been sent to the receiver if the substring is not matched by <span class="argument">regex</span>.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">- stringByReplacingOccurrencesOfRegex:withString:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:options:range:error:" class="code">- stringByReplacingOccurrencesOfRegex:withString:options:range:error:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> </ul> </div> </div> <div class="block method"> <div class="section name softNobr" id="NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:options:range:error:">stringByReplacingOccurrencesOfRegex:&#8203;withString:options:range:error:</div> <div class="section summary">Returns a string created from the characters within <span class="argument">range</span> of the receiver in which all matches of the regular expression <span class="argument">regex</span> using <span class="argument">options</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions.</div> <div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span></span> <span class="hardNobr"><span class="selector">options:</span>(<a href="#RKLRegexOptions" class="code">RKLRegexOptions</a>)<span class="argument">options</span></span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span> <span class="hardNobr"><span class="selector">range:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSRange">NSRange</a>)<span class="argument">range</span></span> <span class="hardNobr"><span class="selector">error:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html">NSError</a> **)<span class="argument">error</span>;</span></div> <div class="section parameters"><div class="header">Parameters</div> <ul> <li> <div class="name">regex</div> <div class="text">A <span class="code">NSString</span> containing a regular expression.</div> </li> <li> <div class="name">options</div> <div class="text">A mask of options specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. Either <span class="code">0</span> or <a href="#RKLRegexOptions_RKLNoOptions" class="code">RKLNoOptions</a> may be used if no options are required.</div> </li> <li> <div class="name">replacement</div> <div class="text">The string to use as the replacement text for matches by <span class="argument">regex</span>. See <a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a> for more information.</div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell">Raises <a href="#RKLICURegexException" class="code">RKLICURegexException</a> if <span class="argument">replacement</span> contains <span class="regex">$</span><span class="argument" title="Decimal Number">n</span> capture references where <span class="argument" title="Decimal Number">n</span> is greater than the number of capture groups in the regular expression <span class="argument">regex</span>.</div></div></div></div> </li> <li> <div class="name">range</div> <div class="text">The range of the receiver to search.</div> </li> <li> <div class="name">error</div> <div class="text">An optional parameter that if set and an error occurs, will contain a <span class="code">NSError</span> object that describes the problem. This may be set to <span class="code">NULL</span> if information about any errors is not required.</div> </li> </ul> </div> <div class="section result"><div class="header">Return Value</div><p>A <span class="code">NSString</span> created from the characters within <span class="argument">range</span> of the receiver in which all matches of the regular expression <span class="argument">regex</span> using <span class="argument">options</span> are replaced with the contents of the <span class="argument">replacement</span> string after performing capture group substitutions. Returns the characters within <span class="argument">range</span> as if <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/clm/NSString/substringWithRange:" class="code">substringWithRange:</a> had been sent to the receiver if the substring is not matched by <span class="argument">regex</span>.</p></div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">- stringByReplacingOccurrencesOfRegex:withString:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:range:" class="code">- stringByReplacingOccurrencesOfRegex:withString:range:</a></li> <li><a href="#ICUSyntax_ICUReplacementTextSyntax" class="section-link">ICU Replacement Text Syntax</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> <li><a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a></li> </ul> </div> </div> <h2>Constants</h2> <div class="block typedef"> <div class="section name" id="RKLRegexOptions">RKLRegexOptions</div> <div class="section summary">Type for regular expression options.</div> <div class="section type">typedef uint32_t RKLRegexOptions;</div> <div class="section discussion"><div class="header">Discussion</div> <p>See <a href="#RegularExpressionOptions" class="section-link">Regular Expression Options</a> for possible values.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <div class="block typedef"> <div class="section name" id="RegularExpressionOptions">Regular Expression Options</div> <div class="section summary">The following flags control various aspects of regular expression matching. The flag values may be specified at the time that a regular expression is used, or they may be specified within the pattern itself using the <span class="regex">(?ismwx-ismwx)</span> pattern options.</div> <div class="section declaration code table"> <div class="top row"><div class="cell">enum {</div></div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLNoOptions">RKLNoOptions</a></div> <div class="equals cell">=</div> <div class="constant cell">0,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLCaseless">RKLCaseless</a></div> <div class="equals cell">=</div> <div class="constant cell">2,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLComments">RKLComments</a></div> <div class="equals cell">=</div> <div class="constant cell">4,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLDotAll">RKLDotAll</a></div> <div class="equals cell">=</div> <div class="constant cell">32,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLMultiline">RKLMultiline</a></div> <div class="equals cell">=</div> <div class="constant cell">8,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexOptions_RKLUnicodeWordBoundaries">RKLUnicodeWordBoundaries</a></div> <div class="equals cell">=</div> <div class="constant cell">256</div> </div> <div class="bottom row"><div class="cell">};</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLNoOptions">RKLNoOptions</div> <div class="text">No regular expression options specified.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLCaseless">RKLCaseless</div> <div class="text">If set, matching will take place in a case-insensitive manner.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLComments">RKLComments</div> <div class="text">If set, allow use of <span class="regex-def">white space</span> and <span class="regex">#comments</span> within patterns.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLDotAll">RKLDotAll</div> <div class="text">If set, a <span class="regex">.</span> in a pattern will match a <span class="regex-def">line terminator</span> in the input text. By default, it will not. Note that a <span class="regex-def">carriage-return</span> / <span class="regex-def">line-feed</span> pair in text behave as a single line terminator, and will match a <span class="hardNobr">single <span class="regex">.</span> (period) in</span> a regular expression pattern.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLMultiline">RKLMultiline</div> <div class="text">Control the behavior of <span class="regex">^</span> and <span class="regex">$</span> in a pattern. By default these will only match at the start and end, respectively, of the input text. If this flag is set, <span class="regex">^</span> and <span class="regex">$</span> will also match at the start and end of each line within the input text.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexOptions_RKLUnicodeWordBoundaries">RKLUnicodeWordBoundaries</div> <div class="text">Controls the behavior of <span class="regex">\b</span> in a pattern. If set, word boundaries are found according to the definitions of word found in <a href="http://www.unicode.org/reports/tr29/" class="section-link NBSP_printURL">Unicode UAX 29 - Text Boundaries</a>. By default, word boundaries are identified by means of a simple classification of characters as either <span class="regex-def">word</span> or <span class="regex-def">non-word</span>, which approximates traditional regular expression behavior. The results obtained with the two options can be quite different in runs of <span class="regex-def">spaces</span> and other <span class="regex-def">non-word</span> characters.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> </div> <div class="section discussion"><div class="header">Discussion</div> <p>Options for controlling the behavior of a regular expression pattern can be controlled in two ways. When the method supports it, options may specified by combining <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flags with the C bitwise OR operator. For example:</p> <div class="box sourcecode"><span class="hardNobr">matchedRange = [aString</span> <span class="hardNobr">rangeOfRegex:@&quot;^(blue|red)$&quot;</span> <span class="hardNobr">options:(RKLCaseless | RKLMultiline)</span> <span class="hardNobr">inRange:range</span> <span class="hardNobr">error:NULL];</span></div> <p>The other way is to specify the options within the regular expression itself, of which there are two ways. The first specifies the options for everything following it, and the other sets the options on a per capture group basis. Options are either <span class="hardNobr"><i>enabled</i>,</span> or following a <span class="hardNobr"><span class="regex">-</span>, <i>disabled</i>.</span> The syntax for both is nearly identical:</p> <table class="standard" summary="Option Specification in Regular Expression Patterns"> <tr><th>Option</th><th>Example</th><th>Description</th></tr> <tr><td><span class="hardNobr"><span class="regex">(?</span><span class="argument">ixsmw</span><span class="regex">-</span><span class="argument">ixsmw</span><span class="regex">)</span>&hellip;</span></td><td class="hardNobr"><span class="regex">(?i)</span>&hellip;</td><td>Enables the <a href="#RKLRegexOptions_RKLCaseless" class="code">RKLCaseless</a> option for everything that follows it. Useful at the beginning of a regular expression to set the desired options.</tr> <tr><td><span class="hardNobr"><span class="regex">(?</span><span class="argument">ixsmw</span><span class="regex">-</span><span class="argument">ixsmw</span><span class="regex">:</span>&hellip;<span class="regex">)</span></span></td><td><span class="regex">(?iw-m:</span>&hellip;<span class="regex">)</span></td><td>Enables the <a href="#RKLRegexOptions_RKLCaseless" class="code">RKLCaseless</a> and <a href="#RKLRegexOptions_RKLUnicodeWordBoundaries" class="code">RKLUnicodeWordBoundaries</a> options and disables <a href="#RKLRegexOptions_RKLMultiline" class="code">RKLMultiline</a> for the capture group enclosed by the parenthesis.</tr> </table> <p>The following table lists the regular expression pattern option character and its corresponding <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> flag:</p> <table class="standard" summary="Regular Expression Pattern Option Flags"> <tr><th>Character</th><th>Option</th></tr> <tr><td><span class="regex">i</span></td><td><a href="#RKLRegexOptions_RKLCaseless" class="code">RKLCaseless</a></td></tr> <tr><td><span class="regex">x</span></td><td><a href="#RKLRegexOptions_RKLComments" class="code">RKLComments</a></td></tr> <tr><td><span class="regex">s</span></td><td><a href="#RKLRegexOptions_RKLDotAll" class="code">RKLDotAll</a></td></tr> <tr><td><span class="regex">m</span></td><td><a href="#RKLRegexOptions_RKLMultiline" class="code">RKLMultiline</a></td></tr> <tr><td><span class="regex">w</span></td><td><a href="#RKLRegexOptions_RKLUnicodeWordBoundaries" class="code">RKLUnicodeWordBoundaries</a></td></tr> </table> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#ICUSyntax_ICURegularExpressionSyntax" class="section-link">ICU Regular Expression Syntax</a></li> <li><a href="http://userguide.icu-project.org/strings/regexp" class="section-link printURL">ICU User Guide - Regular Expressions</a></li> </ul> </div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <div class="block typedef"> <div class="section name" id="RKLRegexEnumerationOptions">RKLRegexEnumerationOptions</div> <div class="section summary">Type for regular expression enumeration options.</div> <div class="section type">typedef NSUInteger RKLRegexEnumerationOptions;</div> <div class="section discussion"><div class="header">Discussion</div> <p>See <a href="#RegularExpressionEnumerationOptions" class="section-link">Regular Expression Enumeration Options</a> for possible values.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"><span class="code">RKLRegexEnumerationOptions</span> is only available if <span class="cpp_flag">RKL_BLOCKS</span> is set.</div></div></div></div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <div class="block typedef"> <div class="section name" id="RegularExpressionEnumerationOptions">Regular Expression Enumeration Options</div> <div class="section summary">The following flags control various aspects of regular expression enumeration.</div> <div class="section declaration code table"> <div class="top row"><div class="cell">enum {</div></div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions">RKLRegexEnumerationNoOptions</a></div> <div class="equals cell">=</div> <div class="constant cell">0UL,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired">RKLRegexEnumerationCapturedStringsNotRequired</a></div> <div class="equals cell">=</div> <div class="constant cell">1UL << 9,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationReleaseStringReturnedByReplacementBlock">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</a></div> <div class="equals cell">=</div> <div class="constant cell">1UL << 10</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX">RKLRegexEnumerationFastCapturedStringsXXX</a></div> <div class="equals cell">=</div> <div class="constant cell">1UL << 11</div> </div> <div class="bottom row"><div class="cell">};</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="constant"> <div class="identifier" id="RKLRegexEnumerationOptions_RKLRegexEnumerationNoOptions">RKLRegexEnumerationNoOptions</div> <div class="text">No regular expression enumeration options specified.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired">RKLRegexEnumerationCapturedStringsNotRequired</div> <div class="text"><p>If set, this indicates that the block does not require the captured strings and <span class="code">NULL</span> will be passed to the blocks <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span> argument.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods will raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException" class="code">NSInvalidArgumentException</a> if <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> and <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> are both set. </div></div></div></div> </div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexEnumerationOptions_RKLRegexEnumerationReleaseStringReturnedByReplacementBlock">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</div> <div class="text">If set, <span class="rkl">RegexKit<i>Lite</i></span> will send the string returned by the block a <span class="code">release</span> message. If garbage collection is active, this flag does nothing. This flag is only valid for the <span class="hardNobr"><span class="code">stringByReplacingOccurrencesOfRegex:</span>&hellip;</span> and <span class="hardNobr"><span class="code">replaceOccurrencesOfRegex:</span>&hellip;</span> groups of methods. See <a href="#RKLRegexEnumerationOptions__Discussion_RKLRegexEnumerationReleaseStringReturnedByReplacementBlock" class="section-link">Regular Expression Enumeration Options - Using RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</a> for more information.</div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods will raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException" class="code">NSInvalidArgumentException</a> if <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationReleaseStringReturnedByReplacementBlock" class="code">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</a> is set and the block enumeration method is not a &#39;Search and Replace&#39; method. </div></div></div></div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX">RKLRegexEnumerationFastCapturedStringsXXX</div> <div class="text"> <p>If set, <span class="rkl">RegexKit<i>Lite</i></span> will create the captured strings that are passed to the blocks <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span> argument in a special way. The enumeration identifier ends in <span class="hardNobr">&hellip;<span class="code">XXX</span></span> to act as a visual reminder that special care must be taken. See <a href="#RKLRegexEnumerationOptions__Discussion_RKLRegexEnumerationFastCapturedStringsXXX" class="section-link">Regular Expression Enumeration Options - Using RKLRegexEnumerationFastCapturedStringsXXX</a> for more information.</p> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"> Methods will raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSInvalidArgumentException" class="code">NSInvalidArgumentException</a> if <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a> and <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> are both set. </div></div></div></div> <div class="box caution" style="margin-top: 1.25em"><div class="table"><div class="row"> <div class="label cell">Caution:</div><div class="message cell"><p><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> is an advanced feature option. <span class="DoNot">Do not</span> use this option unless you fully understand the consequences. Incorrect usage of this option will result in undefined behavior and will probably result in your program crashing.</p></div> </div></div></div> </div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> </div> <div class="section discussion"><div class="header" id="RKLRegexEnumerationOptions__Discussion">Discussion</div> <div class="box important"><div class="table"><div class="row"><div class="label cell">Important:</div><div class="message cell"><span class="code">RKLRegexEnumerationOptions</span> is only available if <span class="cpp_flag">RKL_BLOCKS</span> is set.</div></div></div></div> <p>When the method supports it, enumeration options may specified by combining <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> flags with the C bitwise OR operator.For example:</p> <div class="box sourcecode">RKLRegexEnumerationOptions enumerationOptions = (RKLRegexEnumerationCapturedStringsNotRequired | RKLRegexEnumerationReleaseStringReturnedByReplacementBlock);</div> <p>A typical use of <span class="code">stringByReplacingOccurrencesOfRegex:</span> might be something like the following:</p> <div class="box sourcecode">replacedString = [aString stringByReplacingOccurrencesOfRegex:@&quot;\\w+&quot; options:RKLNoOptions inRange:NSMakeRange(0UL, [aString length]) error:NULL enumerationOptions:RKLRegexEnumerationNoOptions usingBlock:^(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { return((NSString *)[NSString stringWithFormat:@&quot;&lt;%@&gt;&quot;, capturedStrings[0]]); }];</div> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> The above example casts the value returned by <span class="code">stringWithFormat:</span>, which has a return type of <span class="code">id</span>, to <span class="code">NSString *</span> because of a bug in <span class="consoleText">gcc</span> <span class="code">4.2.1-5646</span>. Without the cast, the compiler gives an error that the block does not return a compatible type. <span class="consoleText">clang</span> does not require a cast in order to compile. </div></div></div></div> <p>An alternate way to work around the <span class="consoleText">gcc</span> bug is to explicitly declare the return type of the block. The example below shows how this is done with the changes highlighted:</p> <div class="box sourcecode"><span class="standardFont"><i>stringByReplacingOccurrencesOfRegex:&hellip;</i></span> usingBlock:^<span class="highlight">NSString *</span>(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { return(<span class="highlight">/*(NSString *)*/</span>[NSString stringWithFormat:@&quot;&lt;%@&gt;&quot;, capturedStrings[0]]); }];</div> <div class="header" id="RKLRegexEnumerationOptions__Discussion_RKLRegexEnumerationReleaseStringReturnedByReplacementBlock" style="margin-top: 1em">Using <span class="code">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</span></div> <p>The use of convenience methods like <span class="code">stringWithFormat:</span> can create a lot of temporary strings that are autoreleased. The memory used to hold these temporary strings won&#39;t be reclaimed until the autorelease pool that they are in is released. When performing a replace on a large string, this can end up being a considerable about of memory. If this is becomes a problem in your application, the <span class="code">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</span> enumeration option can be used to reclaim the memory used by these temporary strings immediately. <span class="code">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</span> essentially transfers ownership of the string that is returned by the block to <span class="rkl">RegexKit<i>Lite</i></span>, which then becomes responsible for sending the string a <span class="code">release</span> message when it is no longer needed. Typically this is right after <span class="rkl">RegexKit<i>Lite</i></span> has appended the contents of the returned string to the temporary internal string of all the accumulated replacement strings returned by the block. For example:</p> <div class="box sourcecode">replacedString = [aString stringByReplacingOccurrencesOfRegex:@&quot;\\w+&quot; options:RKLNoOptions inRange:NSMakeRange(0UL, [aString length]) error:NULL enumerationOptions:RKLRegexEnumerationReleaseStringReturnedByReplacementBlock usingBlock:^NSString *(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { return([[NSString alloc] initWithFormat:@&quot;&lt;%@&gt;&quot;, capturedStrings[0]]); }];</div> <p>When using <span class="code">RKLRegexEnumerationReleaseStringReturnedByReplacementBlock</span>, it is also possible to directly return the strings that were passed via <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>. <span class="rkl">RegexKit<i>Lite</i></span> automatically checks if the pointer of the string returned by the block is equal to the pointer of any of the strings it created and passed via <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>, in which case <span class="rkl">RegexKit<i>Lite</i></span> does not send the string that was returned a <span class="code">release</span> message since this would result in over releasing the string object. For example:</p> <div class="box sourcecode">replacedString = [aString stringByReplacingOccurrencesOfRegex:@&quot;\\w+&quot; options:RKLNoOptions inRange:NSMakeRange(0UL, [aString length]) error:NULL enumerationOptions:RKLRegexEnumerationReleaseStringReturnedByReplacementBlock usingBlock:^NSString *(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) { if([capturedStrings[0] isEqual:@&quot;with&quot;]) { return(capturedStrings[0]); } else { return([[NSString alloc] initWithFormat:@&quot;&lt;%@&gt;&quot;, capturedStrings[0]]); } }];</div> <div class="header" id="RKLRegexEnumerationOptions__Discussion_RKLRegexEnumerationFastCapturedStringsXXX" style="margin-top: 1em">Using <span class="code">RKLRegexEnumerationFastCapturedStringsXXX</span></div> <p>Normally, <span class="rkl">RegexKit<i>Lite</i></span> instantiates a new string object for each string passed via <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>. When <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> is set, <span class="rkl">RegexKit<i>Lite</i></span> creates up to <span class="argument">captureCount</span> strings using the <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> function <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFMutableStringRef/Reference/reference.html#//apple_ref/c/func/CFStringCreateMutableWithExternalCharactersNoCopy" class="code">CFStringCreateMutableWithExternalCharactersNoCopy</a> and passes these strings via <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>.</p> <div class="box caution"><div class="table"><div class="row"> <div class="label cell">Caution:</div><div class="message cell"><p><a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> is an advanced feature option. <span class="DoNot">Do not</span> use this option unless you fully understand the consequences. Incorrect usage of this option will result in undefined behavior and will probably result in your program crashing.</p></div> </div></div></div> <p>The reason for doing this is strings created with <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFMutableStringRef/Reference/reference.html#//apple_ref/c/func/CFStringCreateMutableWithExternalCharactersNoCopy" class="code">CFStringCreateMutableWithExternalCharactersNoCopy</a> can have the strings buffer set directly with <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFMutableStringRef/Reference/reference.html#//apple_ref/c/func/CFStringSetExternalCharactersNoCopy" class="code">CFStringSetExternalCharactersNoCopy</a>. This allows <span class="rkl">RegexKit<i>Lite</i></span> to quickly update the strings that were captured by a match and is <b><i>much</i></b> faster than instantiating new strings for each match iteration since the only thing that needs to be updated is the captured strings pointer and length. In fact, the speed of <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> is nearly has fast as <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationCapturedStringsNotRequired" class="code">RKLRegexEnumerationCapturedStringsNotRequired</a>.</p> <p>Special care must be taken when using the strings passed via <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span> when <a href="#RKLRegexEnumerationOptions_RKLRegexEnumerationFastCapturedStringsXXX" class="code">RKLRegexEnumerationFastCapturedStringsXXX</a> has been set. The following rules must be followed:</p> <ul class="square"> <li>The lifetime of the string is the duration of the blocks execution. The string <b><i>can not</i></b> be used or referenced past the closing brace of the block.</li> <li><b><i><u>Do not</u></i></b> mutate any of <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>.</li> <li><b><i><u>Do not</u></i></b> <span class="code">retain</span> or <span class="code">release</span> any of the <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span>.</li> <li><p>If you need the string to exist past the end of the block, a <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/copy" class="code">-copy</a> of the string must be made:</p> <div class="box sourcecode">NSString *copiedString = [[capturedStrings[0] copy] autorelease];</div> </li> </ul> <p>Example usages:</p> <ul class="square"> <li><p>When using <span class="hardNobr"><span class="argument">capturedStrings</span><span class="code">[]</span></span> as an argument to <span class="code">stringWithFormat:</span>, you do not need to make a copy of the captured string:</p> <div class="box sourcecode">[searchString <span class="hardNobr">stringByReplacingOccurrencesOfRegex:regex</span> <span class="hardNobr">usingBlock:^NSString *(NSInteger captureCount,</span> <span class="hardNobr">NSString * const capturedStrings[captureCount],</span> <span class="hardNobr">const NSRange capturedRanges[captureCount],</span> <span class="hardNobr">volatile BOOL * const stop) {</span> NSString *replacedString = NULL; replacedString = [NSString <span class="hardNobr">stringWithFormat:@&quot;{1: &#39;%@&#39;}&quot;,</span> <span class="hardNobr">capturedStrings[1]];</span> // <span class="comment">OK to use directly.</span> return(replacedString); }];</div> <li><p>Adding to a collection:</p> <div class="box sourcecode">[aDictionary <span class="hardNobr">setObject:capturedStrings[0]</span> <span class="hardNobr">forKey:@&quot;aKey&quot;];</span> // <span class="comment"><b><u>Do not</u></b> add a captured string directly to a collection.</span> [aDictionary setObject:<span class="hardNobr">[[capturedStrings[0] copy] autorelease]</span> <span class="hardNobr">forKey:@&quot;aKey&quot;];</span> // <span class="comment"><b><u>Do</u></b> add a copy of the captured string to a collection.</span></div> </li> <li><p>Assigning a captured string to a variable whose scope extends past the blocks:</p> <div class="box sourcecode">__block NSString *foundString = NULL; [searchString <span class="hardNobr">enumerateStringsMatchedByRegex:regex</span> <span class="hardNobr">usingBlock:^(NSInteger captureCount,</span> <span class="hardNobr">NSString * const capturedStrings[captureCount],</span> <span class="hardNobr">const NSRange capturedRanges[captureCount],</span> <span class="hardNobr">volatile BOOL * const stop) {</span> <span class="hardNobr">foundString = capturedStrings[0];</span> // <span class="comment"><b><u>Do not</u></b> assign a captured string to a variable whose scope extends past the blocks.</span> foundString = <span class="hardNobr">[[capturedStrings[0] copy] autorelease];</span> // <span class="comment"><b><u>Do</u></b> assign a copy of the captured string to a variable whose scope extends past the blocks.</span> }];</div> </li> </ul> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#RegexKitLiteNSStringAdditionsReference_Block-basedEnumerationMethods" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> <span class="code"><i>NSString</i></span> Additions Reference - Block-based Enumeration Methods</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html" class="section-link">Blocks Programming Topics</a></li> </ul> </div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <div class="block typedef"> <div class="section name" id="dtrace_utf16ConversionCache_lookupResultFlags">RegexKitLite:::utf16ConversionCache <span class="argument">arg1</span> Flags</div> <div class="section summary">The following flags are used to indicate the status of the result from <span class="argument">arg1</span> <span class="argument">lookupResultFlags</span> of the <span class="code">RegexKitLite:::utf16ConversionCache</span> DTrace probe point.</div> <div class="section declaration code table"> <div class="top row"><div class="cell">enum {</div></div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLCacheHitLookupFlag">RKLCacheHitLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 0,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLConversionRequiredLookupFlag">RKLConversionRequiredLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 1,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLSetTextLookupFlag">RKLSetTextLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 2,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLDynamicBufferLookupFlag">RKLDynamicBufferLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 3,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLErrorLookupFlag">RKLErrorLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 4,</div> </div> <div class="enum row"> <div class="identifier cell"><a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLEnumerationBufferLookupFlag">RKLEnumerationBufferLookupFlag</a></div> <div class="equals cell">=</div> <div class="constant cell">1 &lt;&lt; 5</div> </div> <div class="bottom row"><div class="cell">};</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLCacheHitLookupFlag">RKLCacheHitLookupFlag</div> <div class="text">If set, there was a successful lookup hit. This flag is only set if <span class="code">RKLConversionRequiredLookupFlag</span> is also set.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLConversionRequiredLookupFlag">RKLConversionRequiredLookupFlag</div> <div class="text">If set, direct access to a strings <span class="code">UTF-16</span> buffer was not available and a conversion was required.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLSetTextLookupFlag">RKLSetTextLookupFlag</div> <div class="text">If set, the ICU <span class="code">uregex_setText()</span> function was called in order to set the compiled regular expression to a buffer.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLDynamicBufferLookupFlag">RKLDynamicBufferLookupFlag</div> <div class="text">If set, the strings size was large enough to require the use of the dynamically sized conversion buffer.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLErrorLookupFlag">RKLErrorLookupFlag</div> <div class="text">If set, there was some kind of error during the <span class="code">UTF-16</span> conversion process.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 3.0 and later.</div> </div> <div class="constant"> <div class="identifier" id="dtrace_utf16ConversionCache_lookupResultFlags_RKLEnumerationBufferLookupFlag">RKLEnumerationBufferLookupFlag</div> <div class="text">If set, the probe was fired due to a blocks enumeration. The conversion result is one time use only and is only available to the block enumeration that required it.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="#DTrace_RegexKitLiteProbePoints__utf16ConversionCache" class="code">RegexKitLite:::utf16ConversionCache</a></li> </ul> </div> </div> <h3 id="RegexKitLiteNSErrorErrorDomains"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</h3> <div class="block constants"> <div class="section summary">The following <span class="code">NSError</span> error domains are defined.</div> <div class="section declaration table"> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexErrorDomain">RKLICURegexErrorDomain</a>;</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="section constant"> <div class="identifier" id="RKLICURegexErrorDomain">RKLICURegexErrorDomain</div> <div class="text">ICU Regular Expression Errors.</div> </div> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="section-link printURL_small">NSError Class Reference</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> </ul> </div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <h3 id="RegexKitLiteNSExceptionExceptionNames"><span class="rkl">RegexKit<i>Lite</i></span> NSException Exception Names</h3> <div class="block constants"> <div class="section summary">The following <span class="code">NSException</span> exception names are defined.</div> <div class="section declaration table"> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexException">RKLICURegexException</a>;</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="section constant"> <div class="identifier" id="RKLICURegexException">RKLICURegexException</div> <div class="text">ICU Regular Expression Exceptions</div> </div> </div> <div class="section discussion"><div class="header">Discussion</div> <p>Returns a user info dictionary populated with keys as defined in <a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a>.</p> </div> <div class="section availability"><div class="header">Availability</div><p>Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</p></div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/Reference/Reference.html" class="section-link printURL_small">NSException Class Reference</a></li> <li><a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a></li> </ul> </div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> <h3 id="RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</h3> <div class="block constants"> <div class="section declaration table"> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexEnumerationOptionsErrorKey">RKLICURegexEnumerationOptionsErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexErrorCodeErrorKey">RKLICURegexErrorCodeErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexErrorNameErrorKey">RKLICURegexErrorNameErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexLineErrorKey">RKLICURegexLineErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexOffsetErrorKey">RKLICURegexOffsetErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexPreContextErrorKey">RKLICURegexPreContextErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexPostContextErrorKey">RKLICURegexPostContextErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexRegexErrorKey">RKLICURegexRegexErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexRegexOptionsErrorKey">RKLICURegexRegexOptionsErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexReplacedCountErrorKey">RKLICURegexReplacedCountErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexReplacedStringErrorKey">RKLICURegexReplacedStringErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexReplacementStringErrorKey">RKLICURegexReplacementStringErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexSubjectRangeErrorKey">RKLICURegexSubjectRangeErrorKey</a>;</div></div> <div class="row"><div class="name cell">extern <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> * const <a href="#RKLICURegexSubjectStringErrorKey">RKLICURegexSubjectStringErrorKey</a>;</div></div> </div> <div class="section constants"><div class="header">Constants</div> <div class="section constant"> <div class="identifier" id="RKLICURegexEnumerationOptionsErrorKey">RKLICURegexEnumerationOptionsErrorKey</div> <div class="text">The <a href="#RKLRegexEnumerationOptions" class="code">RKLRegexEnumerationOptions</a> enumeration options specified.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexErrorCodeErrorKey">RKLICURegexErrorCodeErrorKey</div> <div class="text">The error code returned by the ICU library function calls <span class="argument">status</span> argument.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 2.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexErrorNameErrorKey">RKLICURegexErrorNameErrorKey</div> <div class="text">The string returned by invoking <a href="http://www.icu-project.org/apiref/icu4c/utypes_8h.html#89eb455526bb29bf5350ee861d81df92" class="code">u_errorName</a> with the error code <a href="#RKLICURegexErrorCodeErrorKey" class="code">RKLICURegexErrorCodeErrorKey</a>. Example: <span class="quotedText">U_REGEX_RULE_SYNTAX</span>.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexLineErrorKey">RKLICURegexLineErrorKey</div> <div class="text">The line number where the error occurred in the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexOffsetErrorKey">RKLICURegexOffsetErrorKey</div> <div class="text">The offset from the beginning of the line where the error occurred in the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexPreContextErrorKey">RKLICURegexPreContextErrorKey</div> <div class="text">Up to <span class="code">16</span> characters leading up to the cause error in the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexPostContextErrorKey">RKLICURegexPostContextErrorKey</div> <div class="text">Up to <span class="code">16</span> characters after the cause error in the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexRegexErrorKey">RKLICURegexRegexErrorKey</div> <div class="text">The regular expression that caused the error.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexRegexOptionsErrorKey">RKLICURegexRegexOptionsErrorKey</div> <div class="text">The <a href="#RKLRegexOptions" class="code">RKLRegexOptions</a> regular expression options specified.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 1.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexReplacedCountErrorKey">RKLICURegexReplacedCountErrorKey</div> <div class="text">The number of times a replacement was performed.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexReplacedStringErrorKey">RKLICURegexReplacedStringErrorKey</div> <div class="text">The replaced string result after performing the search and replace operations.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexReplacementStringErrorKey">RKLICURegexReplacementStringErrorKey</div> <div class="text">The replacement template string used to perform search and replace operations.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexSubjectRangeErrorKey">RKLICURegexSubjectRangeErrorKey</div> <div class="text">The range of the subject string that was being matched by the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> <div class="section constant"> <div class="identifier" id="RKLICURegexSubjectStringErrorKey">RKLICURegexSubjectStringErrorKey</div> <div class="text">The string that was being matched by the regular expression.</div> <div class="text">Available in <span class="rkl">RegexKit<i>Lite</i></span> 4.0 and later.</div> </div> </div> <div class="section discussion"><div class="header">Discussion</div> <p>Different error keys will be present depending on the type of error encountered.</p> </div> <div class="section seealso"><div class="header">See Also</div> <ul> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html" class="section-link printURL_small">NSError Class Reference</a></li> <li><a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSException_Class/Reference/Reference.html" class="section-link printURL_small">NSException Class Reference</a></li> <li><a href="#RegexKitLiteNSErrorErrorDomains" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError Error Domains</a></li> <li><a href="#RegexKitLiteNSExceptionExceptionNames" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSException Exception Names</a></li> </ul> </div> <div class="section declared_in"><div class="header">Declared In</div> <div class="file">RegexKitLite.h</div> </div> </div> </div> <div class="printPageBreakAfter"> <h2 id="ReleaseInformation">Release Information</h2> <div class="chrono"> <div class="entry"> <div class="banner"><span class="date">2008/03/23</span><span class="bannerItemSpacer">-</span><span class="release">1.0</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>Initial release.</p> </div> </div> <div class="entry"> <div class="banner"><span class="date">2008/03/28</span><span class="bannerItemSpacer">-</span><span class="release">1.1</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>Changes:</p> <ul class="square"> <li>Added the method <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" title="Clears the cached information about strings." class="code">clearStringCache</a>.</li> <li>Updated the documentation with information about searching <span class="code">NSMutableString</span> strings, and when to use <a href="#NSString_RegexKitLiteAdditions__.clearStringCache" title="Clears the cached information about strings." class="code">clearStringCache</a>.</li> </ul> <p>Bug fixes:</p> <ul class="square"> <li>Fixed a bug that for strings that required <span class="code hardNobr">UTF-16</span> conversion, the conversion from the previous string that required conversion may have been re-used for the current string, even though the two strings are different and the new string requires conversion.</li> <li>Updated the internal inconsistency exception macro to correctly handle <span class="hardNobr">non-<span class="code">ASCII</span></span> file names.</li> </ul> </div> </div> <div class="entry"> <div class="banner"><span class="date">2008/04/01</span><span class="bannerItemSpacer">-</span><span class="release">1.2</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>Changes:</p> <ul class="square"> <li>Updated and clarified the documentation regarding adding <span class="rkl">RegexKit<i>Lite</i></span> to an Xcode project.</li> <li>Created Xcode 3 DocSet documentation.</li> </ul> </div> </div> <div class="entry"> <div class="banner"><span class="date">2008/07/07</span><span class="bannerItemSpacer">-</span><span class="release">2.0</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>New features:</p> <ul class="square"> <li>The ability to split a string in to a <span class="code">NSArray</span> with a regular expression.</li> <li>Search and replace using common <span class="hardNobr"><span class="regex">$</span><span class="argument">n</span></span> capture substitution in the replacement string.</li> <li>Support for Leopards Garbage Collection</li> </ul> <p>Changes:</p> <ul class="square"> <li>A new compile time configuration option, <span class="cpp_flag">RKL_FAST_MUTABLE_CHECK</span>, enables the use of a private, non-public <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> function to determine if the string that will be searched is immutable. This allows many of the mutation safety checks to be skipped for that string and can significantly improve the performance of repeated matches on the same immutable <span class="code">NSString</span>. For safety, this option is disabled by default.</li> <li>Gives a warning at compile time if the minimum <span class="hardNobr">Mac OS X</span> target <span class="hardNobr">is &lt; 10.3,</span> which is the first version that shipped with the ICU library.</li> <li>Compile time tunable setting of how much of the stack can be used before switching to heap based storage. Changed by setting <span class="cpp_flag">RKL_STACK_LIMIT</span> to the maximum number of bytes to use from the stack. Defaults to <span class="code">131072</span>, or <span class="code">128Kbytes</span>. By default in Cocoa the main thread has a stack size of <span class="code">8Mbytes</span> and additional threads have a stack size of <span class="code">512Kbytes</span>.</li> <li>New <span class="code">NSException</span> name for <span class="rkl">RegexKit<i>Lite</i></span> specific exceptions, <a href="#RKLICURegexException" class="code">RKLICURegexException</a>.</li> <li>Garbage Collection is safe to use in <span class="hardNobr">"mixed-mode"</span> Garbage Collection applications. When compiled with Garbage Collection <span class="hardNobr">support (<span class="code">-fobjc-gc</span>),</span> <span class="rkl">RegexKit<i>Lite</i></span> will dynamically select either Garbage Collection or manual memory management at run-time depending on whether or not Garbage Collection is enabled and active.</li> </ul> <p>New <span class="code">NSString</span> Methods:</p> <ul class="square"> <li><div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<span class="selector">componentsSeparatedByRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</div></li> <li><div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="selector">stringByReplacingOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span>;</div></li> </ul> <p>New <span class="code">NSMutableString</span> Methods:</p> <ul class="square"> <li><div class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSUInteger">NSUInteger</a>)<span class="selector">replaceOccurrencesOfRegex:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span> <span class="hardNobr"><span class="selector">withString:</span>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">replacement</span></span>;</div></li> </ul> </div> </div> <div class="entry"> <div class="banner"><span class="date">2008/07/12</span><span class="bannerItemSpacer">-</span><span class="release">2.1</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>Bug fixes:</p> <ul class="square"> <li>Fixed a bug dealing with the <span class="code">UTF-16</span> conversion cache. A bug could cause the text in the conversion buffer to be incorrectly used for the wrong string.</li> </ul> </div> </div> <div class="entry"> <div class="banner"><span class="date">2008/10/19</span><span class="bannerItemSpacer">-</span><span class="release">2.2</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release contains several large documentation additions and a few bug fixes. No new major functionality was added.</p> <p>Documentation Changes:</p> <ul class="square"> <li>Added a section covering <a href="#ICUSyntax_ICURegularExpressionCharacterClasses">ICU Regular Expression Character Classes</a></li> <li>Added a section covering <a href="#ICUSyntax_UnicodeProperties">Unicode Properties</a>, which are specified in a regular expression with <span class="hardNobr"><span class="regex">\p{</span><i>Unicode Property Name</i><span class="regex">}</span></span> and <span class="hardNobr"><span class="regex">\P{</span><i>Unicode Property Name</i><span class="regex">}</span></span>.</li> <li>Added the <a href="#RegexKitLiteCookbook"><span class="rkl">RegexKit<i>Lite</i></span> Cookbook</a> section. Special <i>Copy to Clipboard</i> functionality is enabled for Safari users that allows a regular expression in this document that is selected and <i>Copied to the Clipboard</i> to be automatically escaped so the regular expression can be pasted directly in to your source code, ready to be used, with no additional work required.</li> <li>Added the <a href="#Epilogue">Epilogue</a> section. This section is meant to be less formal, where I can place bits and pieces that don&#39;t fit elsewhere or editorialize on some topic.</li> <li>A number of small additions, deletions, and edits through out the documentation.</li> </ul> <p>Changes:</p> <ul class="square"> <li>A new compile time configuration option, <span class="cpp_flag">RKL_METHOD_PREPEND</span>, can be used to add custom prefix to all the <span class="rkl">RegexKit<i>Lite</i></span> methods. For example, setting <span class="cpp_flag">RKL_METHOD_PREPEND</span> to <span class="code">xyz_</span> would cause <span class="code">stringByReplacingOccurrencesOfRegex:withString:</span> to become <span class="code">xyz_stringByReplacingOccurrencesOfRegex:withString:</span>. This is for users who prefer that any category additions to the core classes, such as <span class="code">NSString</span>, have a user defined prefix to prevent the possibility of user defined method names interfering with later system defined method names.</li> <li>Support for iPhone low memory notifications. When it can be determined at compile time that the iPhone is being targeted, the preprocessor flag <span class="cpp_flag">RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS</span> is enabled to add code that automatically registers for low memory notifications on the iPhone. When a low memory notification is received, <span class="rkl">RegexKit<i>Lite</i></span> will flush all its caches, freeing the memory used to hold the cached data.</li> </ul> <p>Bug fixes:</p> <ul class="square"> <li> <p><a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2105213&amp;group_id=%20204582&amp;atid=990188" class="printURL">Bug 2105213</a></p> <p>Fixed a bug in <a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">stringByReplacingOccurrencesOfRegex:withString:</a> and <a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">replaceOccurrencesOfRegex:withString:</a> where if the receiver was an empty string (i.e., <span class="code">@&quot;&quot;</span>), then <span class="rkl">RegexKit<i>Lite</i></span> would throw an exception because the ICU library reported an error. This turned out to be a bug in the ICU library itself in the <span class="code">uregex_reset()</span> function (and the methods it calls to perform its work). A bug was opened with the ICU project: <a href="http://bugs.icu-project.org/trac/ticket/6545">http://bugs.icu-project.org/trac/ticket/6545</a>. A work-around for the buggy behavior was put in place so that if the ICU library reports a <span class="code">U_INDEX_OUTOFBOUNDS_ERROR</span> error for a string with a length of zero, that error is ignored since it is spurious. Thanks go to Andy Kim for reporting this.</p> </li> <li> <p><a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2050825&amp;group_id=%20204582&amp;atid=990188" class="printURL">Bug 2050825</a></p> <p>Fixed a bug with <span class="code">NSScannedOption</span> when targeting the iPhone. <span class="code">NSScannedOption</span> is not available on the iPhone, so C Pre-Processor statements were added to ensure that <span class="code">NSScannedOption</span> is not referenced when Objective-C Garbage Collection is not enabled. Thanks go to Shaun Inman for reporting this first.</p> </li> <li>Fixed a bug in <a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:withString:" class="code">stringByReplacingOccurrencesOfRegex:withString:</a> and <a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:withString:" class="code">replaceOccurrencesOfRegex:withString:</a> where an internal assertion exception would be thrown if the string to search and the replacement string were both zero length strings (i.e., <span class="code">@&quot;&quot;</span>).</li> </ul> </div> </div> <div class="entry" id="ReleaseInformation_30"> <div class="banner"><span class="date">2009/05/06</span><span class="bannerItemSpacer">-</span><span class="release">3.0</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release of <span class="rkl">RegexKit<i>Lite</i></span> is a major release that includes new features, new APIs, and a number of bug fixes.</p> <p>New Features:</p> <ul class="square"> <li>DTrace support. This release includes <span class="rkl">RegexKit<i>Lite</i></span> specific DTrace provider probe points that allow you to monitor the effectiveness of <span class="rkl">RegexKit<i>Lite</i></span>&#39;s caches. DTrace support can be enabled with the compile time configuration option <span class="cpp_flag">RKL_DTRACE</span>.</li> <li>Easy support for custom built ICU libraries. A new compile time configuration option, <span class="cpp_flag">RKL_APPEND_TO_ICU_FUNCTIONS</span>, can be used to append a string to the ICU functions called by <span class="rkl">RegexKit<i>Lite</i></span>. Custom builds of the ICU library include the ICU version appended to all functions by default and this feature allows you to easily retarget <span class="rkl">RegexKit<i>Lite</i></span> to your custom build. Example usage: <span class="consoleText">-DRKL_APPEND_TO_ICU_FUNCTIONS=_4_0</span></li> </ul> <p>New <span class="code">NSString</span> Methods:</p> <ul class="square"> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<a href="#NSString_RegexKitLiteAdditions__-arrayOfCaptureComponentsMatchedByRegex:" class="selector">arrayOfCaptureComponentsMatchedByRegex:</a>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<a href="#NSString_RegexKitLiteAdditions__-captureComponentsMatchedByRegex:" class="selector">captureComponentsMatchedByRegex:</a>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<a href="#NSString_RegexKitLiteAdditions__-captureCount" class="selector">captureCount</a>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html">NSArray</a> *)<a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="selector">componentsMatchedByRegex:</a>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (void)<a href="#NSString_RegexKitLiteAdditions__-flushCachedRegexData" class="selector">flushCachedRegexData</a>;</span></div></li> <li><div class="signature"><span class="hardNobr">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/tdef/BOOL">BOOL</a>)<a href="#NSString_RegexKitLiteAdditions__-isRegexValid" class="selector">isRegexValid</a>;</span></div></li> </ul> <p>Deprecated Functionality:</p> <ul class="square"> <li> <p><span class="signature"><span class="hardNobr">+ (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger">NSInteger</a>)<a href="#NSString_RegexKitLiteAdditions__.captureCountForRegex:" class="selector">captureCountForRegex:</a>(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span></span> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></p> <p>Use of <span class="code">captureCountForRegex:</span> is deprecated in favor of <a href="#NSString_RegexKitLiteAdditions__-captureCount" class="code">captureCount</a>.</p> </li> <li> <p><span class="signature">- (<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSEnumerator_Class/Reference/Reference.html">NSEnumerator</a> *)matchEnumeratorWithRegex:(<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html">NSString</a> *)<span class="argument">regex</span>;</span> and <span class="code">RKLMatchEnumerator</span> <span class="deprecated">Deprecated in <span class="rkl">RegexKit<i>Lite</i></span> 3.0</span></p> <p>The example code for <span class="code">RKLMatchEnumerator</span> available in <span class="file">examples/RKLMatchEnumerator.h</span> and <span class="file">examples/RKLMatchEnumerator.m</span> has been deprecated in favor of <a href="#NSString_RegexKitLiteAdditions__-componentsMatchedByRegex:" class="code">componentsMatchedByRegex:</a>.</p> </li> </ul> <p class="standout">Changes that effect the results that are returned:</p> <ul class="square"> <li> <p>When the regular expression matched the tail end of the string to search, <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">componentsSeparatedByRegex:</a> would incorrectly add a zero length string to the results returned.</p> <div class="box sourcecode">NSArray *splitArray = [@&quot;Bob, Tom, Sam,&quot; componentsSeparatedByRegex:@&quot;,\\s*&quot;]; // <span class="comment">{ @&quot;Bob&quot;, @&quot;Tom&quot;, @&quot;Sam&quot;, @&quot;&quot; } &lt;- RegexKitLite &le; v2.2.</span> // <span class="comment">{ @&quot;Bob&quot;, @&quot;Tom&quot;, @&quot;Sam&quot; } &lt;- RegexKitLite &ge; v3.0.</span></div> </li> <li> <p>The results returned by <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">componentsSeparatedByRegex:</a> were found to differ from the expected results when zero-width assertions, such as <span class="regex">\b</span>, were used. Prior to v3.0, regular expressions that matched zero characters would be considered a &#39;match&#39;, and a zero length string would be added to the results array. The expected results are the results that are returned by the <span class="quotedText">perl</span> <span class="code">split()</span> function, which does not create a zero length string in such cases. ICU ticket #<a href="http://bugs.icu-project.org/trac/ticket/6826" class="printURL">6826</a>.</p> <div class="box sourcecode">NSArray *splitArray = [@&quot;I|at|ice I eat rice&quot; componentsSeparatedByRegex:@&quot;\\b\\s*&quot;]; // <span class="comment">ICU : { @&quot;&quot;, @&quot;I&quot;, @&quot;|&quot;, @&quot;at&quot;, @&quot;|&quot;, @&quot;ice&quot;, @&quot;&quot;, @&quot;I&quot;, @&quot;&quot;, @&quot;eat&quot;, @&quot;&quot;, @&quot;rice&quot; } &lt;- RegexKitLite &le; v2.2.</span> // <span class="comment">perl: { @&quot;I&quot;, @&quot;|&quot;, @&quot;at&quot;, @&quot;|&quot;, @&quot;ice&quot;, @&quot;I&quot;, @&quot;eat&quot;, @&quot;rice&quot; } &lt;- RegexKitLite &ge; v3.0.</span></div> </li> <li>As part of the <span class="hardNobr">64-bit</span> tidy, a check of the length of a string that is passed to <span class="rkl">RegexKit<i>Lite</i></span>, and therefore ICU, was added to ensure that the length is less than <span class="code">INT_MAX</span>. If the length of the string <span class="hardNobr">is &ge; <span class="code">INT_MAX</span>,</span> then <span class="rkl">RegexKit<i>Lite</i></span> will raise <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/doc/c_ref/NSRangeException" class="code">NSRangeException</a>. The value of <span class="hardNobr"><span class="code">INT_MAX</span> is 2<sup>31</sup>-1 (<span class="code">0x7fffffff</span>).</span> This was done because ICU uses the <span class="code">int</span> type for representing offset values.</li> </ul> <p>Other Changes:</p> <ul class="square"> <li>Ticket #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2027975&amp;group_id=204582&amp;atid=990188" class="printURL">2027975</a> - Request for <span class="code">captureCount</span> like functionality.</li> <li>Ticket #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2779301&amp;group_id=204582&amp;atid=990191" class="printURL">2779301</a> - Request for <span class="code">componentsMatchedByRegex:</span> functionality.</li> <li>Ticket #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2779965&amp;group_id=204582&amp;atid=990188" class="printURL">2779965</a> - Request that documentation be updated with how to match a literal <span class="consoleText">\</span> with a regex specified using a string literal: <span class="consoleText">@&quot;\\\\&quot;;</span>.</li> <li>Ticket #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2786878&amp;group_id=204582&amp;atid=990191" class="printURL">2786878</a> - Request for <span class="code">isRegexValid</span> functionality.</li> <li>The GCC variable <span class="code">cleanup</span> <span class="hardNobr code">__attribute__()</span> is now used to provide an extra safety net around the use of the <span class="rkl">RegexKit<i>Lite</i></span> spin lock. The <span class="code">cleanup</span> function ensures that if the spin lock was locked by a function that it was also unlocked by the function. If a function obtains the lock but does not unlock it, the <span class="code">cleanup</span> function forcibly unlocks the spin lock.</li> <li>Minor GC changes. Some minor changes in the way heap buffers were allocated was required to support the new methods that return a <span class="code">NSArray</span>.</li> <li><span class="hardNobr">64-bit</span> cleanup. Various literal numeric constant values had either <span class="code">L</span> or <span class="code">UL</span> appended to them if they were used with <span class="code">NSInteger</span>, <span class="code">NSUInteger</span>, or various other <span class="hardNobr">&#39;<span class="code">long</span>&#39;</span> data types.</li> <li><span class="hardNobr">64-bit</span> cleanup. Added checks to verify that a strings length is &lt; <span class="code">INT_MAX</span> and throw an exception if it isn&#39;t. This check was added because ICU uses signed <span class="hardNobr">32-bit</span> <span class="code">int</span> values to represent offsets.</li> <li>Changed some macros to static inline functions for compile-time prototype checking.</li> <li>Updated <span class="hardNobr file">examples/NSString-HexConversion.m</span>. <span class="hardNobr">64-bit</span> tidies.</li> <li>Updated <span class="hardNobr file">examples/RKLMatchEnumerator.h</span>. Added the deprecated attribute to <span class="code">matchEnumeratorWithRegex:</span>.</li> <li>Updated <span class="hardNobr file">examples/RKLMatchEnumerator.m</span>. <span class="hardNobr">64-bit</span> tidies. Added a preprocessor warning that <span class="code">RKLMatchEnumerator</span> has been deprecated in favor of <span class="code">componentsSeparatedByRegex:</span>.</li> <li>Updated the documentations visual style to better match the style currently used by Apple.</li> <li>Many small DocSet tweaks and improvements.</li> </ul> <p>Bug fixes:</p> <ul class="square"> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2319200&amp;group_id=204582&amp;atid=990188" class="printURL">2319200</a> - The documentation for <span class="code">stringByReplacingOccurrencesOfRegex:withString:</span> (and related methods) was updated. The text for the Returned Value section was obviously copy and pasted from somewhere else and never updated. This has been fixed.</li> <li>Bug #<a href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=2408447&amp;group_id=204582&amp;atid=990188" class="printURL">2408447</a> - <span class="code">stringByReplacingOccurrencesOfRegex:</span> bug fixed. There was a bug in ICU that would cause a search and replace operation to fail with <span class="code">U_BUFFER_OVERFLOW_ERROR</span>, which would then cause <span class="rkl">RegexKit<i>Lite</i></span> to throw <a href="#RKLICURegexException" class="code">RKLICURegexException</a>, if the length of the replaced string was significantly longer than the original string. ICU ticket #<a href="http://bugs.icu-project.org/trac/ticket/6656" class="printURL">6656</a></li> <li><span class="code">componentsSeparatedByRegex:</span> bug fixed. When the regular expression matched the tail end of the string, an extra zero length string was incorrectly added to the results.</li> <li><span class="code">componentsSeparatedByRegex:</span> bug fixed. The results returned by the ICU function <span class="hardNobr code">uregex_split()</span> was found to be different that the results returned by the <span class="quotedText">perl</span> <span class="hardNobr code">split()</span> function. ICU ticket #<a href="http://bugs.icu-project.org/trac/ticket/6826" class="printURL">6826</a></li> <li><span class="code">rangeOfRegex</span>, <span class="code">stringByMatching:</span> bug fixed. A bug was fixed where the <span class="code">inRange:</span> parameter was not correctly honored.</li> <li>If <span class="rkl">RegexKit<i>Lite</i></span> was able to get direct access to a strings <span class="hardNobr code">UTF-16</span> buffer, there was a very remote chance that <span class="rkl">RegexKit<i>Lite</i></span> would continue to use a pointer to a strings older <span class="hardNobr code">UTF-16</span> buffer if the string mutated and allocated a new buffer. The pointer to a strings direct buffer is now verified before each use.</li> <li><span class="code">isMatchedByRegex:inRange:</span> was never documented. Fixed.</li> </ul> </div> </div> <!-- release notes 3.0 --> <div class="entry" id="ReleaseInformation_31"> <div class="banner"><span class="date">2009/05/15</span><span class="bannerItemSpacer">-</span><span class="release">3.1</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release of <span class="rkl">RegexKit<i>Lite</i></span> is a bug fix release.</p> <p>Bug Fixes:</p> <ul class="square"> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2790480&amp;group_id=204582&amp;atid=990188" class="printURL">2790480</a> - If a regular expression had an error, as detected by ICU, then under some circumstances the <span class="code">lastCacheSlot</span> variable would not be properly cleared. As a result, this would cause the pointer to the compiled regular expression to be <span class="code">NULL</span>. The <span class="code">NULL</span> value would be caught by the run&#8209;time assertion checks if they were not disabled via <span class="cpp_flag">NS_BLOCK_ASSERTIONS</span>, otherwise it would most likely lead to a crash.</li> </ul> </div> </div> <!-- release notes 3.1 --> <div class="entry" id="ReleaseInformation_32"> <div class="banner"><span class="date">2009/11/04</span><span class="bannerItemSpacer">-</span><span class="release">3.2</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release of <span class="rkl">RegexKit<i>Lite</i></span> is a bug fix release.</p> <p>Bug Fixes:</p> <ul class="square"> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2828966&amp;group_id=204582&amp;atid=990188" class="printURL">2828966</a> - Fixed a minor bug that caused compiling on <span class="hardNobr">Mac OS X 10.4</span> to fail. Changed the header include line from <span class="code hardNobr">#include &lt;objc/runtime.h&gt;</span>, which is available only on <span class="hardNobr">Mac OS X &ge; 10.5</span>, to <span class="code hardNobr">#include &lt;objc/objc-runtime.h&gt;</span>, which is available on <span class="hardNobr">Mac OS X &ge; 10.4</span>.</li> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2862398&amp;group_id=204582&amp;atid=990188" class="printURL">2862398</a> - Modified the logic for determining if the cached <span class="code hardNobr">UTF-16</span> conversion is valid for the string to be searched. Previously, <span class="rkl">RegexKit<i>Lite</i></span> used a combination of the string to be searched <span class="code">hash</span> and <span class="code">length</span> to determine if the cached <span class="code hardNobr">UTF-16</span> conversion was a match. For speed, <span class="code">NSString</span> only uses a fixed number of characters to calculate the hash. This means that as the length of a string grows, the hash function becomes less effective at detecting differences between strings. The original intent behind the <span class="code hardNobr">UTF-16</span> conversion cache logic was to be able to re-use the <span class="code hardNobr">UTF-16</span> conversion for strings that were <span class="hardNobr">&quot;the same&quot;</span> <span class="hardNobr">(i.e., hash equality),</span> but were different instantiations <span class="hardNobr">(i.e., pointer inequality).</span> On reflection, it was decided that the more likely real-world case would be strings that would share the same hash value, but actually be slightly different. <span class="rkl">RegexKit<i>Lite</i></span> now requires that the <span class="code">NSString</span> pointer, as well as the <span class="code">hash</span> and <span class="code">length</span>, be the same as the string used for the cached <span class="code hardNobr">UTF-16</span> conversion.</li> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2879356&amp;group_id=204582&amp;atid=990188" class="printURL">2879356</a> - <span class="code">arrayOfCaptureComponentsMatchedByRegex:</span>, <span class="code">captureComponentsMatchedByRegex:</span>, <span class="code">componentsMatchedByRegex:</span>, and <span class="code">componentsSeparatedByRegex:</span> bug fixed. Originally reported by Jesse Grosjean. Duplicate bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2890342&amp;group_id=204582&amp;atid=990188" class="printURL">2890342</a>. If a regex matched a part of the string that included the very end of the string, subsequent matches would incorrectly return that the regex did not match the string. Clearing the cache, either manually or because another regex match replaced the affected cache slot, would clear the condition.</li> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;atid=990188&amp;aid=2890810&amp;group_id=204582" class="printURL">2890810</a> - <span class="code">stringByReplacingOccurrencesOfRegex:</span> bug fixed. If the size of the buffer needed to hold the replaced string was larger than the initial estimated buffer size, ICU should return an error of <span class="code">U_BUFFER_OVERFLOW_ERROR</span>. However, due to a bug in ICU (see bug #<a href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=2408447&amp;group_id=204582&amp;atid=990188" class="printURL">2408447</a>, ICU ticket #<a href="http://bugs.icu-project.org/trac/ticket/6656" class="printURL">6656</a>), this error was not reported correctly and a workaround was implemented. A rare corner case could cause ICU to return <span class="code">U_STRING_NOT_TERMINATED_WARNING</span> during the time that <span class="rkl">RegexKit<i>Lite</i></span> was calculating the size of the buffer needed to hold all of the replaced string. When this happened it would cause <span class="rkl">RegexKit<i>Lite</i></span> to miss the <span class="code">U_BUFFER_OVERFLOW_ERROR</span> error needed to resize the buffer.</li> </ul> </div> </div> <!-- release notes 3.2 --> <div class="entry" id="ReleaseInformation_33"> <div class="banner"><span class="date">2009/11/07</span><span class="bannerItemSpacer">-</span><span class="release">3.3</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release of <span class="rkl">RegexKit<i>Lite</i></span> is a bug fix release.</p> <p>Bug Fixes:</p> <ul class="square"> <li>Bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;atid=990188&amp;aid=2893824&amp;group_id=204582" class="printURL">2893824</a> - Fixed a minor bug that caused compiling with the iPhone device SDK to fail. This is related to the <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 3.2</span> fix for bug #<a href="http://sourceforge.net/tracker/?func=detail&amp;aid=2828966&amp;group_id=204582&amp;atid=990188" class="printURL">2828966</a>. It turns out that the iPhone simulator SDK has the header file <span class="file">objc/objc-runtime.h</span>, but the iPhone device SDK only has the header file <span class="file">objc/runtime.h</span>. <span class="rkl">RegexKit<i>Lite</i></span> will now conditionally use <span class="code hardNobr">#include &lt;objc/runtime.h&gt;</span> when targeting the iPhone or <span class="hardNobr">Mac OS X &ge; 10.5</span>, and <span class="code hardNobr">#include &lt;objc/objc-runtime.h&gt;</span> when targeting <span class="hardNobr">Mac OS X &le; 10.4</span>.</li> </ul> </div> </div> <!-- release notes 3.3 --> <div class="entry" id="ReleaseInformation_40"> <div class="banner"><span class="date">2010/04/18</span><span class="bannerItemSpacer">-</span><span class="release">4.0</span></div> <div class="bannerSpacer"></div> <div class="content"> <p>This release of <span class="rkl">RegexKit<i>Lite</i></span> is a major release that includes new features, new APIs, and bug fixes.</p> <p class="standout">API Compatibility Changes:</p> <ul class="square"> <li> <p>The <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/index.html" class="code">NSMutableString</a> <span class="hardNobr"><span class="code">replaceOccurrencesOfRegex:</span>&hellip;</span> methods now return a result of type <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSInteger" class="code">NSInteger</a>, whereas <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> &lt; 4.0</span> returned a result of type <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/c/tdef/NSUInteger" class="code">NSUInteger</a>. This change, while technically breaking API compatibility, is likely to be completely backwards compatible for most users. The change was made so that errors, such as an invalid regular expression, can be distinguished from a search and replace operation that replaced zero occurrences. An error condition that is not an exception now returns a value of <span class="code">-1</span>. Prior to <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0,</span> the only way to distinguish between a search and replace operation that replaced zero occurrences and an error that prevented a search and replace from taking place was to use a <span class="hardNobr"><span class="code">replaceOccurrencesOfRegex:</span>&hellip;</span> method with an <span class="code">error:</span> parameter.</p> </li> </ul> <p class="standout">Changes that effect the results that are returned:</p> <ul class="square"> <li> <p>The results returned by <a href="#NSString_RegexKitLiteAdditions__-componentsSeparatedByRegex:" class="code">componentsSeparatedByRegex:</a> were found to differ from the expected results for some regex patterns. For example, prior to v4.0, when the regular expression <span class="regex">.</span> (dot, match any character) was used to split a string, <span class="rkl">RegexKit<i>Lite</i></span> returned an array of seven zero length strings. The expected results are the results that are returned by the <span class="quotedText">perl</span> <span class="code">split()</span> function&ndash; the equivalent of a <span class="code">NSArray</span> with zero items in it.</p> <div class="box sourcecode">NSArray *splitArray = [@&quot;abc.def&quot; componentsSeparatedByRegex:@&quot;.&quot;]; // <span class="comment">{ @&quot;&quot;, @&quot;&quot;, @&quot;&quot;, @&quot;&quot;, @&quot;&quot;, @&quot;&quot;, @&quot;&quot; } &lt;- RegexKitLite &le; v3.3.</span> // <span class="comment">{ } &lt;- RegexKitLite &ge; v4.0 &amp; perl.</span></div> </li> </ul> <p>New features:</p> <ul class="square"> <li> <p>Documentation now available in PDF format.</p> <p>The <span class="rkl">RegexKit<i>Lite</i></span> documentation is now available in PDF format. The PDF version is ideal for making printed copies of the documentation.</p> </li> <li> <p>Improved compiled regular expression cache.</p> <p><span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> versions &lt; 4.0</span> used a direct mapped, or 1-way set associative, cache. <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0</span> uses a 4-way set associative cache. In general, a <span class="hardNobr"><i>n</i>-way</span> set associative cache, where <span class="hardNobr"><i>n</i> &gt; <span class="code">1</span>,</span> has fewer misses than a direct mapped cache. Entries in a set are managed on a least recently used, or LRU, basis. This means that when a compiled regular expression is added to the cache, the entry in a set that is the least recently used is the one chosen to hold the new compiled regular expression.</p> <p>In benchmark tests, the old compiled regular expression cache required a <b><i>dramatically</i></b> larger cache size to achieve the same effectiveness <span class="hardNobr">(i.e.,</span> the likelihood that the regular expression was already in the cache) as the new compiled regular expression cache. Retrieving a cached compiled regular expression is <b><i>541.3</i></b> times faster<sup>&dagger;</sup> than actually compiling the regular expression:</p> <div style="margin-left: 2ex; margin-top: 1em;"> <table class="standard"> <tr><th>Retrieve</th><th>Time</th><th>Rate (per second)</th></tr> <tr><td><b>Cached</b></td><td align="right"><span class="hardNobr">51 ns</span></td><td align="right">19,680,762</td></tr> <tr><td><b>Compile</b></td><td align="right"><span class="hardNobr">27,560 ns</span></td><td align="right">36,285</td></tr> </table> <p><sup>&dagger;</sup>Timing done a <span class="hardNobr">MacBook Pro 2.66GHz</span> running <span class="hardNobr">Mac OS X 10.6.2.</span></p> </div> </li> <li> <p>Improved <span class="code">UTF-16</span> conversion cache.</p> <p>The <span class="code">UTF-16</span> conversion cache now uses the same 4-way set associative cache system as the compiled regular expression cache. For strings that required a <span class="code">UTF-16</span> conversion, <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> versions &lt; 4.0</span> used two buffers for caching <span class="code">UTF-16</span> conversions&mdash; a small, fixed sized buffer for &#39;small&#39; strings <span class="hardNobr">(&le; <span class="code">2048</span></span> characters by default), and a dynamically sized buffer for &#39;large&#39; strings. <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0</span> keeps the same fixed and dynamic size dichotomy, but now each type contains four buffers which are reused on a least recently used basis.</p> </li> <li> <p>Blocks support.</p> <p>Although support for blocks was introduced with <span class="hardNobr">Mac OS X 10.6</span>, you can still use blocks on <span class="hardNobr">Mac OS X 10.5</span> and <span class="hardNobr">iPhone &ge; 2.2</span> by using <a href="http://code.google.com/p/plblocks/" class="printURL">Plausible Blocks</a>. This solution provides a compiler and runtime that has been back-ported from the <span class="hardNobr">Mac OS X 10.6</span> <span class="hardNobr">Snow Leopard</span> sources.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <span class="rkl">RegexKit<i>Lite</i></span> checks if the C preprocessor define <span class="cpp_flag">NS_BLOCKS_AVAILABLE</span> is set to <span class="code">1</span> to automatically determine if blocks functionality should be enabled. Typically <span class="cpp_flag">NS_BLOCKS_AVAILABLE</span> is only set to <span class="code">1</span> when using the standard developer tools and the minimum version of <span class="hardNobr">Mac OS X</span> supported is set to <span class="hardNobr">10.6</span>. <span class="rkl">RegexKit<i>Lite</i></span> blocks support can be explicitly enabled by setting <span class="cpp_flag">RKL_BLOCKS</span> to <span class="code">1</span> <span class="hardNobr">(i.e.,</span> <span class="consoleText">-DRKL_BLOCKS=1</span>). The behavior is undefined if <span class="cpp_flag">RKL_BLOCKS</span> is set to <span class="code">1</span> and the compiler does not support the blocks language extension or if the run-time does not support blocks. </div></div></div></div> <div class="section seealso" style="margin-top: 0.75em"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://code.google.com/p/plblocks/" class="section-link printURL">Plausible Blocks - PLBlocks</a></li> </ul> </div> </li> </ul> <p>New <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html" class="code">NSString</a> Methods:</p> <ul class="square"> <li><a href="#NSString_RegexKitLiteAdditions__-dictionaryByMatchingRegex:withKeysAndCaptures:" class="code">- dictionaryByMatchingRegex:withKeysAndCaptures:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:" class="code">- arrayOfDictionariesByMatchingRegex:withKeysAndCaptures:</a></li> </ul> <p>New Block-based <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html" class="code">NSString</a> Methods:</p> <ul class="square"> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsMatchedByRegex:usingBlock:" class="code">- enumerateStringsMatchedByRegex:usingBlock:</a></li> <li><a href="#NSString_RegexKitLiteAdditions__-enumerateStringsSeparatedByRegex:usingBlock:" class="code">- enumerateStringsSeparatedByRegex:usingBlock:</a> <li><a href="#NSString_RegexKitLiteAdditions__-stringByReplacingOccurrencesOfRegex:usingBlock:" class="code">- stringByReplacingOccurrencesOfRegex:usingBlock:</a></li> </ul> <p>New Block-based <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/index.html" class="code">NSMutableString</a> Methods:</p> <ul class="square"> <li><a href="#NSMutableString_RegexKitLiteAdditions__-replaceOccurrencesOfRegex:usingBlock:" class="code">- replaceOccurrencesOfRegex:usingBlock:</a></li> </ul> <p>Other changes:</p> <ul class="square"> <li>Improved performance. Many small performance tweaks and optimizations were made to frequently used code paths.</li> <li>The meaning of <span class="cpp_flag">RKL_CACHE_SIZE</span> changed. This compile-time preprocessor tunable now controls the number of &quot;sets&quot; in the compiled regular expression cache, and each &quot;set&quot; contains four entries. This means that the maximum number of potential compiled regular expressions that can be cached is <span class="cpp_flag">RKL_CACHE_SIZE</span> times four. Like previous versions, <span class="cpp_flag">RKL_CACHE_SIZE</span> should always be a prime number to maximize the use of the cache.</li> <li><span class="cpp_flag">RKL_CACHE_SIZE</span> changed to <span class="code">13</span>. The total number of compiled regular expressions that can be cached is <span class="code hardNobr">13 * 4</span>, or <span class="code">52</span>. This is a 126% increase from previous versions of <span class="rkl">RegexKit<i>Lite</i></span> which had a default value of <span class="code">23</span> for <span class="cpp_flag">RKL_CACHE_SIZE</span>.</li> <li>Added the flag <a href="#dtrace_utf16ConversionCache_lookupResultFlags_RKLEnumerationBufferLookupFlag" class="code">RKLEnumerationBufferLookupFlag</a> to the DTrace <a href="#dtrace_utf16ConversionCache_lookupResultFlags" class="code">RegexKitLite:::utf16ConversionCache</a> flags.</li> <li>Added a number of new keys to <a href="#RegexKitLiteNSErrorandNSExceptionUserInfoDictionaryKeys" class="section-link"><span class="rkl">RegexKit<i>Lite</i></span> NSError and NSException User Info Dictionary Keys</a>.</li> </ul> <p>Bug fixes:</p> <ul class="square"> <li>If the ICU library returned a status of <span class="code">U_STRING_NOT_TERMINATED_WARNING</span> during a search and replace operation, <span class="rkl">RegexKit<i>Lite</i></span> erred on the side of caution and treated it as a failure due to the numerous search and replace bugs in the past. <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0</span> continues to err on the side of caution, but now treats <span class="code">U_STRING_NOT_TERMINATED_WARNING</span> as if the ICU library had returned a status of <span class="code">U_BUFFER_OVERFLOW_ERROR</span>.</li> <li>The <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/index.html" class="code">NSMutableString</a> <span class="hardNobr"><span class="code">replaceOccurrencesOfRegex:</span>&hellip;</span> methods could have returned a value <span class="hardNobr">&gt; <span class="code">0</span>,</span> the replaced count, even if no actual replacements were performed. This would occur if an error was encountered during the search and replace, in which case the replaced count was not correctly reset to <span class="code">0</span>. <span class="hardNobr"><span class="rkl">RegexKit<i>Lite</i></span> 4.0</span> changed the <span class="hardNobr"><span class="code">replaceOccurrencesOfRegex:</span>&hellip;</span> API so that a value of <span class="code">-1</span> could be returned to indicate that an error was encountered.</li> <li><span class="code">componentsSeparatedByRegex:</span> bug fixed. The results returned were found to be different that the results returned by the <span class="consoleText">perl</span> <span class="code">split()</span> function.</li> </ul> </div> </div> <!-- release notes 4.0 --> </div> </div> <div class="printPageBreakAfter"> <h2 id="Epilogue">Epilogue</h2> <h3>Coding Style</h3> <p>One noticeable break in style conventions is in line lengths. There was a time when 80 column limits made a lot of sense as it was the lowest common denominator. Today, a modern computer screen can display much more than just 80 columns. Even an iPhone, which has a screen size of <span class="hardNobr">320x480,</span> can display 96 columns by 24 rows of the usual <span class="hardNobr">Terminal.app</span> Monaco 10pt font (5x13 pixels) in landscape mode. Because of this, my personal style is not to have an arbitrary limit on line lengths. This allows for much more code to fit on the screen at once, which I&#39;ve heard referred to as &quot;Man&mdash;Machine Interface Bandwidth&quot;. While you can always page up and down, the simple movement of your eye is almost always an order of magnitude faster. Paging through code also tends to break your concentration as you briefly try to mentally orientate yourself with the freshly displayed text and where the section of code is that you&#39;re looking for.</p> <p>I try to group a line around relevancy so that based on the start of the line you can quickly determine if the rest of the line is applicable. Clearly the number of spaces used to indent a block plays a similar role, it allows you to quickly visually establish the logical boundaries of what lines of code are applicable. I also try to horizontally align related statements since your eye tends to be extremely sensitive to such visual patterns. For example, in variable declaration and initialization, I try to align the type declaration and the <span class="code">=</span> (equal sign) across multiple lines. This tends to cause the declaration type, the variable name, and the value assigned to visually <i>pop</i>. Without the alignment, you typically have to scan back and forth along a line to separate and find a variable name and its initialization value. Sometimes line breaks and horizontal alignment are done purely on what&#39;s subjectively aesthetically pleasing and allows the eye to quickly <i>flow</i> over the code.</p> <p>The source code of <span class="rkl">RegexKit<i>Lite</i></span> isn&#39;t exactly what you&#39;d call clean, there&#39;s more than a few crufty <b>C</b> barnacles in there. There is usually a choice between two polar opposites and in this case it&#39;s between elegant, easy to maintain and comprehend code, and speed. If you use regular expressions for very long, you will undoubtedly encounter a situation where you need to scan through tens of megabytes of text and the speed of your regular expression matching loop needs to be faster. <b><i>A lot faster.</i></b> <span class="rkl">RegexKit<i>Lite</i></span> was written to go fast, and the source code style reflects this choice.</p> <h4>The Need for Speed</h4> <p>A significant amount of time was spent using Shark to optimize the critical sections of <span class="rkl">RegexKit<i>Lite</i></span>. This included tweaking even the most insignificant details, such as the order of boolean expressions in <span class="code">if()</span> statements to minimize the number of branches that would have to be evaluated to determine if the statement is true or false. Wherever possible, <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> is used directly. This avoids the overhead of an <span class="hardNobr">Objective-C</span> message dispatch, which would invariably end up calling the exact same <a href="http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CoreFoundation_Collection/index.html" class="section-link hardNobr">Core Foundation</a> function anyways.</p> <p>Even the cache has what is essentially a cache&mdash; the last regular expression used. Each time a regular expression is used, the compiled ICU regular expression must be retrieved from the cache, or if it does not exist in the cache, instantiated. Checking the cache involves calculating the remainder of the regular expression strings hash modulo the cache size prime, which is a moderately expensive division and multiplication operation. However, checking if the regular expression being retrieved this time is exactly the same as the last regular expression retrieved is just a fast and simple comparison check. As it turns out, this is very often the case. Even the functions are arranged in such a way that the compiler will often inline everything in to one large aggregate function, eliminating the overhead of a function call in many places.</p> <p>Normally, this kind of micro-optimization is completely unjustified. A rough rule of thumb is that 80% of your programs execution time is spent in 20% of your programs code. The only code worth optimizing is the 20% that is heavily executed. If your program makes heavy use of regular expressions, such as a loop that scans megabytes of text using regular expressions, <span class="rkl">RegexKit<i>Lite</i></span> is almost guaranteed to be a part of the 20% of code where most of the execution time is spent. The release notes for <a href="http://osx.iusethis.com/app/versions/coteditor">CotEditor</a> would seem to indicate that all this effort has paid off for at least one user:</p> <div class="box quote"> <p style="margin-bottom: 1em;" class="quotedText">More than 10.4 when running on the color process to review the details of the definition of a regular expression search RegexKitLite adopted, 0.9.3, as compared to the speed of color from 1.5 to 4 times as much improved.</p> <div class="box note"><div class="table"><div class="row"><div class="label cell">Note:</div><div class="message cell"> <p>This is an automatic machine translation from Japanese to English.</p> </div></div></div></div> </div> <h3>Documentation</h3> <p>Clearly documentation has been a high priority for this project. Documentation is always hard to write and good documentation is exponentially harder still. The vast majority of &#39;development effort and time&#39; is spent on the documentation. It&#39;s always hard to judge the quality and effectiveness of something you wrote, so hopefully the extra effort is worth it and appreciated.</p> <p>As an aside and a small rant, I have no idea how anyone manages to build so-called &#39;web applications&#39;. I waste a truly unbelievable amount of time trying to accomplish the simplest of things in HTML, which is then multiplied when I check for &#39;compatibility&#39; with different browsers and their various popular versions. What a joke, and that&#39;s just for this &#39;simple&#39; documentation. Though I do have to give kudos to the Safari / WebKit guys, it always seems to be a lot easier to get the result you&#39;re looking for with the WebKit engine. The little things add so much: shadows, round rects, gradients, CSS animations, the canvas element, etc.</p> <h3>Questions about licensing, including in your software, etc</h3> <div class="faq"> <div class="qa"> <div class="q">What do I need to do to include <span class="rkl">RegexKit<i>Lite</i></span> in my software?</div> <div class="a">Not much. The <i class="hardNobr">BSD License</i> is very permissive. In short, you just need to &#39;acknowledge&#39; your use of it. Safari&#39;s <span class="context-menu hardNobr">Help </span><span class="submenuArrow">&#9658;</span><span class="context-menu"> Acknowledgements</span> is a good example of this.</div> </div> <div class="qa"> <div class="q">I am selling a &#39;closed-source&#39; commercial application. I would like to use <span class="rkl">RegexKit<i>Lite</i></span> in it, how much will it cost?</div> <div class="a"><span class="rkl">RegexKit<i>Lite</i></span> is free for any use.</div> </div> <div class="qa"> <div class="q">Do I have to distribute the source with my application?</div> <div class="a">No. Unlike the <a href="http://www.gnu.org/licenses/licenses.html" class="section-link printURL">GNU GPL License</a>, there is no requirement that you include or make the source code available, even if you release a &quot;compiled, binaries only&quot; end product.</div> </div> <div class="qa"> <div class="q">What about modifications to <span class="rkl">RegexKit<i>Lite</i></span>? Do I have to make any changes that I make available? Or contribute them back to the author of <span class="rkl">RegexKit<i>Lite</i></span>?</div> <div class="a">You may make any modifications you want and are under no obligation to release those changes to anyone.</div> </div> <div class="qa"> <div class="q">Why the <i class="hardNobr">BSD License</i>?</div> <div class="a"><p>It&#39;s a well known license. If you are part of a Large Corporate Organization, chances are the Corporate Lawyers have Decided whether or not the use of source code licensed under the <i class="hardNobr">BSD License</i> is Acceptable or not. This can be a godsend for anyone who has to deal with such situations.</p> <p>It also expresses a few things I think are perfectly reasonable:</p> <ol> <li>Give credit where credit is due.</li> <li>There is no warranty, so use it at your own risk.</li> <li>You can&#39;t hold the author responsible.</li> </ol> <p>The first point is prescribed by most professional ethics already. Plus, it&#39;s always nice to see where your stuff ends up and how it&#39;s being used. The other points make explicit what should already be obvious. After all, you get what you pay for.</p> </div> </div> </div> </div> <div> <h2 id="LicenseInformation">License Information</h2> <p><span class="rkl">RegexKit<i>Lite</i></span> is distributed under the terms of the <i class="hardNobr">BSD License</i>, as specified below.</p> <div class="section seealso"><div class="header">See Also</div> <ul class="offset"> <li><a href="http://en.wikipedia.org/wiki/BSD_license" class="section-link printURL">Wikipedia - BSD License</a></li> <li><a href="http://www.linfo.org/bsdlicense.html" class="section-link printURL">The Linux Information Project - BSD License Definition</a></li> </ul> </div> <h3>License</h3> <div class="sourceLicense"><p>Copyright &copy; 2008-2010, John Engelhart</p> <p>All rights reserved.</p> <p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p> <ul> <li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li> <li>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</li> <li>Neither the name of the Zang Industries nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</li> </ul> <p class="disclaimer">THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p> </div> </div> <div class="screenOnly"> <!-- Used by javascript from various shiny chrome bits. --> <div class="screenOnly" style="display: none;" id="pulseOutline">&nbsp;</div> <div class="screenOnly copyToClipboardHUD" style="display: none;" id="copyToClipboardHUD"> <div class="top" id="copyToClipboardHUDTop"> <div class="padding"> <div class="copiedAs">Copied to Clipboard as:</div> <div class="regex copyToClipboardHUDRegex" id="copyToClipboardHUDRegex">&hellip;</div> </div> </div> </div> </div> </body> </html>
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/RegexKitLite/RegexKitLite/RegexKitLite.m
Objective-C
// // RegexKitLite.m // http://regexkit.sourceforge.net/ // Licensed under the terms of the BSD License, as specified below. // /* Copyright (c) 2008-2010, John Engelhart All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Zang Industries nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <CoreFoundation/CFBase.h> #include <CoreFoundation/CFArray.h> #include <CoreFoundation/CFString.h> #import <Foundation/NSArray.h> #import <Foundation/NSDictionary.h> #import <Foundation/NSError.h> #import <Foundation/NSException.h> #import <Foundation/NSNotification.h> #import <Foundation/NSRunLoop.h> #ifdef __OBJC_GC__ #import <Foundation/NSGarbageCollector.h> #define RKL_STRONG_REF __strong #define RKL_GC_VOLATILE volatile #else // __OBJC_GC__ #define RKL_STRONG_REF #define RKL_GC_VOLATILE #endif // __OBJC_GC__ #if (defined(TARGET_OS_EMBEDDED) && (TARGET_OS_EMBEDDED != 0)) || (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0)) || (defined(MAC_OS_X_VERSION_MIN_REQUIRED) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <objc/runtime.h> #else #include <objc/objc-runtime.h> #endif #include <libkern/OSAtomic.h> #include <mach-o/loader.h> #include <AvailabilityMacros.h> #include <dlfcn.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #import "RegexKitLite.h" // If the gcc flag -mmacosx-version-min is used with, for example, '=10.2', give a warning that the libicucore.dylib is only available on >= 10.3. // If you are reading this comment because of this warning, this is to let you know that linking to /usr/lib/libicucore.dylib will cause your executable to fail on < 10.3. // You will need to build your own version of the ICU library and link to that in order for RegexKitLite to work successfully on < 10.3. This is not simple. #if MAC_OS_X_VERSION_MIN_REQUIRED < 1030 #warning The ICU dynamic shared library, /usr/lib/libicucore.dylib, is only available on Mac OS X 10.3 and later. #warning You will need to supply a version of the ICU library to use RegexKitLite on Mac OS X 10.2 and earlier. #endif //////////// #pragma mark Compile time tunables #ifndef RKL_CACHE_SIZE #define RKL_CACHE_SIZE (13UL) #endif #if RKL_CACHE_SIZE < 1 #error RKL_CACHE_SIZE must be a non-negative number greater than 0. #endif // RKL_CACHE_SIZE < 1 #ifndef RKL_FIXED_LENGTH #define RKL_FIXED_LENGTH (2048UL) #endif #if RKL_FIXED_LENGTH < 1 #error RKL_FIXED_LENGTH must be a non-negative number greater than 0. #endif // RKL_FIXED_LENGTH < 1 #ifndef RKL_STACK_LIMIT #define RKL_STACK_LIMIT (128UL * 1024UL) #endif #if RKL_STACK_LIMIT < 0 #error RKL_STACK_LIMIT must be a non-negative number. #endif // RKL_STACK_LIMIT < 0 #ifdef RKL_APPEND_TO_ICU_FUNCTIONS #define RKL_ICU_FUNCTION_APPEND(x) _RKL_CONCAT(x, RKL_APPEND_TO_ICU_FUNCTIONS) #else // RKL_APPEND_TO_ICU_FUNCTIONS #define RKL_ICU_FUNCTION_APPEND(x) x #endif // RKL_APPEND_TO_ICU_FUNCTIONS #if defined(RKL_DTRACE) && (RKL_DTRACE != 0) #define _RKL_DTRACE_ENABLED 1 #endif // defined(RKL_DTRACE) && (RKL_DTRACE != 0) // These are internal, non-public tunables. #define _RKL_FIXED_LENGTH ((NSUInteger)RKL_FIXED_LENGTH) #define _RKL_STACK_LIMIT ((NSUInteger)RKL_STACK_LIMIT) #define _RKL_SCRATCH_BUFFERS (5UL) #if _RKL_SCRATCH_BUFFERS != 5 #error _RKL_SCRATCH_BUFFERS is not tunable, it must be set to 5. #endif // _RKL_SCRATCH_BUFFERS != 5 #define _RKL_PREFETCH_SIZE (64UL) #define _RKL_DTRACE_REGEXUTF8_SIZE (64UL) // A LRU Cache Set holds 4 lines, and the LRU algorithm uses 4 bits per line. // A LRU Cache Set has a type of RKLLRUCacheSet_t and is 16 bits wide (4 lines * 4 bits per line). // RKLLRUCacheSet_t must be initialized to a value of 0x0137 in order to work correctly. typedef uint16_t RKLLRUCacheSet_t; #define _RKL_LRU_CACHE_SET_INIT ((RKLLRUCacheSet_t)0x0137U) #define _RKL_LRU_CACHE_SET_WAYS (4UL) #if _RKL_LRU_CACHE_SET_WAYS != 4 #error _RKL_LRU_CACHE_SET_WAYS is not tunable, it must be set to 4. #endif // _RKL_LRU_CACHE_SET_WAYS != 4 #define _RKL_REGEX_LRU_CACHE_SETS ((NSUInteger)(RKL_CACHE_SIZE)) #define _RKL_REGEX_CACHE_LINES ((NSUInteger)((NSUInteger)(_RKL_REGEX_LRU_CACHE_SETS) * (NSUInteger)(_RKL_LRU_CACHE_SET_WAYS))) // Regex String Lookaside Cache parameters. #define _RKL_REGEX_LOOKASIDE_CACHE_BITS (6UL) #if _RKL_REGEX_LOOKASIDE_CACHE_BITS < 0 #error _RKL_REGEX_LOOKASIDE_CACHE_BITS must be a non-negative number and is not intended to be user tunable. #endif // _RKL_REGEX_LOOKASIDE_CACHE_BITS < 0 #define _RKL_REGEX_LOOKASIDE_CACHE_SIZE (1LU << _RKL_REGEX_LOOKASIDE_CACHE_BITS) #define _RKL_REGEX_LOOKASIDE_CACHE_MASK ((1LU << _RKL_REGEX_LOOKASIDE_CACHE_BITS) - 1LU) // RKLLookasideCache_t should be large enough to to hold the maximum number of cached regexes, or (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS). #if (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) <= (1 << 8) typedef uint8_t RKLLookasideCache_t; #elif (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) <= (1 << 16) typedef uint16_t RKLLookasideCache_t; #else // (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) > (1 << 16) typedef uint32_t RKLLookasideCache_t; #endif // (RKL_CACHE_SIZE * _RKL_LRU_CACHE_SET_WAYS) ////////////// #pragma mark - #pragma mark GCC / Compiler macros #if defined (__GNUC__) && (__GNUC__ >= 4) #define RKL_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) #define RKL_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) #define RKL_PREFETCH(ptr) __builtin_prefetch(ptr) #define RKL_PREFETCH_UNICHAR(ptr, off) { const char *p = ((const char *)(ptr)) + ((off) * sizeof(UniChar)) + _RKL_PREFETCH_SIZE; RKL_PREFETCH(p); RKL_PREFETCH(p + _RKL_PREFETCH_SIZE); } #define RKL_HAVE_CLEANUP #define RKL_CLEANUP(func) RKL_ATTRIBUTES(cleanup(func)) #else // defined (__GNUC__) && (__GNUC__ >= 4) #define RKL_ATTRIBUTES(attr, ...) #define RKL_EXPECTED(cond, expect) (cond) #define RKL_PREFETCH(ptr) #define RKL_PREFETCH_UNICHAR(ptr, off) #define RKL_CLEANUP(func) #endif // defined (__GNUC__) && (__GNUC__ >= 4) #define RKL_STATIC_INLINE static __inline__ RKL_ATTRIBUTES(always_inline) #define RKL_ALIGNED(arg) RKL_ATTRIBUTES(aligned(arg)) #define RKL_UNUSED_ARG RKL_ATTRIBUTES(unused) #define RKL_WARN_UNUSED RKL_ATTRIBUTES(warn_unused_result) #define RKL_WARN_UNUSED_CONST RKL_ATTRIBUTES(warn_unused_result, const) #define RKL_WARN_UNUSED_PURE RKL_ATTRIBUTES(warn_unused_result, pure) #define RKL_WARN_UNUSED_SENTINEL RKL_ATTRIBUTES(warn_unused_result, sentinel) #define RKL_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) #define RKL_WARN_UNUSED_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) #define RKL_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) #define RKL_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) RKL_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) #if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) #define RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) #else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) #define RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) RKL_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) #endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) #ifdef _RKL_DTRACE_ENABLED #define RKL_UNUSED_DTRACE_ARG #else // _RKL_DTRACE_ENABLED #define RKL_UNUSED_DTRACE_ARG RKL_ATTRIBUTES(unused) #endif // _RKL_DTRACE_ENABLED //////////// #pragma mark - #pragma mark Assertion macros // These macros are nearly identical to their NSCParameterAssert siblings. // This is required because nearly everything is done while rkl_cacheSpinLock is locked. // We need to safely unlock before throwing any of these exceptions. // @try {} @finally {} significantly slows things down so it's not used. #define RKLCHardAbortAssert(c) do { int _c=(c); if(RKL_EXPECTED(!_c, 0L)) { NSLog(@"%@:%ld: Invalid parameter not satisfying: %s\n", [NSString stringWithUTF8String:__FILE__], (long)__LINE__, #c); abort(); } } while(0) #define RKLCAssertDictionary(d, ...) rkl_makeAssertDictionary(__PRETTY_FUNCTION__, __FILE__, __LINE__, (d), ##__VA_ARGS__) #define RKLCDelayedHardAssert(c, e, g) do { id *_e=(e); int _c=(c); if(RKL_EXPECTED(_e == NULL, 0L) || RKL_EXPECTED(*_e != NULL, 0L)) { goto g; } if(RKL_EXPECTED(!_c, 0L)) { *_e = RKLCAssertDictionary(@"Invalid parameter not satisfying: %s", #c); goto g; } } while(0) #ifdef NS_BLOCK_ASSERTIONS #define RKLCAbortAssert(c) #define RKLCDelayedAssert(c, e, g) #define RKL_UNUSED_ASSERTION_ARG RKL_ATTRIBUTES(unused) #else // NS_BLOCK_ASSERTIONS #define RKLCAbortAssert(c) RKLCHardAbortAssert(c) #define RKLCDelayedAssert(c, e, g) RKLCDelayedHardAssert(c, e, g) #define RKL_UNUSED_ASSERTION_ARG #endif // NS_BLOCK_ASSERTIONS #define RKL_EXCEPTION(e, f, ...) [NSException exceptionWithName:(e) reason:rkl_stringFromClassAndMethod((self), (_cmd), (f), ##__VA_ARGS__) userInfo:NULL] #define RKL_RAISE_EXCEPTION(e, f, ...) [RKL_EXCEPTION(e, f, ##__VA_ARGS__) raise] //////////// #pragma mark - #pragma mark Utility functions and macros RKL_STATIC_INLINE BOOL NSRangeInsideRange(NSRange cin, NSRange win) RKL_WARN_UNUSED; RKL_STATIC_INLINE BOOL NSRangeInsideRange(NSRange cin, NSRange win) { return((((cin.location - win.location) <= win.length) && ((NSMaxRange(cin) - win.location) <= win.length)) ? YES : NO); } #define NSMakeRange(loc, len) ((NSRange){.location=(NSUInteger)(loc), .length=(NSUInteger)(len)}) #define CFMakeRange(loc, len) ((CFRange){.location= (CFIndex)(loc), .length= (CFIndex)(len)}) #define NSNotFoundRange ((NSRange){.location=(NSUInteger)NSNotFound, .length= 0UL}) #define NSMaxiumRange ((NSRange){.location= 0UL, .length= NSUIntegerMax}) // These values are used to help tickle improper usage. #define RKLIllegalRange ((NSRange){.location= NSIntegerMax, .length= NSIntegerMax}) #define RKLIllegalPointer ((void * RKL_GC_VOLATILE)0xBAD0C0DE) //////////// #pragma mark - #pragma mark Exported NSString symbols for exception names, error domains, error keys, etc NSString * const RKLICURegexException = @"RKLICURegexException"; NSString * const RKLICURegexErrorDomain = @"RKLICURegexErrorDomain"; NSString * const RKLICURegexEnumerationOptionsErrorKey = @"RKLICURegexEnumerationOptions"; NSString * const RKLICURegexErrorCodeErrorKey = @"RKLICURegexErrorCode"; NSString * const RKLICURegexErrorNameErrorKey = @"RKLICURegexErrorName"; NSString * const RKLICURegexLineErrorKey = @"RKLICURegexLine"; NSString * const RKLICURegexOffsetErrorKey = @"RKLICURegexOffset"; NSString * const RKLICURegexPreContextErrorKey = @"RKLICURegexPreContext"; NSString * const RKLICURegexPostContextErrorKey = @"RKLICURegexPostContext"; NSString * const RKLICURegexRegexErrorKey = @"RKLICURegexRegex"; NSString * const RKLICURegexRegexOptionsErrorKey = @"RKLICURegexRegexOptions"; NSString * const RKLICURegexReplacedCountErrorKey = @"RKLICURegexReplacedCount"; NSString * const RKLICURegexReplacedStringErrorKey = @"RKLICURegexReplacedString"; NSString * const RKLICURegexReplacementStringErrorKey = @"RKLICURegexReplacementString"; NSString * const RKLICURegexSubjectRangeErrorKey = @"RKLICURegexSubjectRange"; NSString * const RKLICURegexSubjectStringErrorKey = @"RKLICURegexSubjectString"; // Used internally by rkl_userInfoDictionary to specify which arguments should be set in the NSError userInfo dictionary. enum { RKLUserInfoNone = 0UL, RKLUserInfoSubjectRange = 1UL << 0, RKLUserInfoReplacedCount = 1UL << 1, RKLUserInfoRegexEnumerationOptions = 1UL << 2, }; typedef NSUInteger RKLUserInfoOptions; //////////// #pragma mark - #pragma mark Type / struct definitions // In general, the ICU bits and pieces here must exactly match the definition in the ICU sources. #define U_STRING_NOT_TERMINATED_WARNING -124 #define U_ZERO_ERROR 0 #define U_INDEX_OUTOFBOUNDS_ERROR 8 #define U_BUFFER_OVERFLOW_ERROR 15 #define U_PARSE_CONTEXT_LEN 16 typedef struct uregex uregex; // Opaque ICU regex type. typedef struct UParseError { // This must be exactly the same as the 'real' ICU declaration. int32_t line; int32_t offset; UniChar preContext[U_PARSE_CONTEXT_LEN]; UniChar postContext[U_PARSE_CONTEXT_LEN]; } UParseError; // For use with GCC's cleanup() __attribute__. enum { RKLLockedCacheSpinLock = 1UL << 0, RKLUnlockedCacheSpinLock = 1UL << 1, }; enum { RKLSplitOp = 1UL, RKLReplaceOp = 2UL, RKLRangeOp = 3UL, RKLArrayOfStringsOp = 4UL, RKLArrayOfCapturesOp = 5UL, RKLCapturesArrayOp = 6UL, RKLDictionaryOfCapturesOp = 7UL, RKLArrayOfDictionariesOfCapturesOp = 8UL, RKLMaskOp = 0xFUL, RKLReplaceMutable = 1UL << 4, RKLSubcapturesArray = 1UL << 5, }; typedef NSUInteger RKLRegexOp; enum { RKLBlockEnumerationMatchOp = 1UL, RKLBlockEnumerationReplaceOp = 2UL, }; typedef NSUInteger RKLBlockEnumerationOp; typedef struct { RKL_STRONG_REF NSRange * RKL_GC_VOLATILE ranges; NSRange findInRange, remainingRange; NSInteger capacity, found, findUpTo, capture, addedSplitRanges; size_t size, stackUsed; RKL_STRONG_REF void ** RKL_GC_VOLATILE rangesScratchBuffer; RKL_STRONG_REF void ** RKL_GC_VOLATILE stringsScratchBuffer; RKL_STRONG_REF void ** RKL_GC_VOLATILE arraysScratchBuffer; RKL_STRONG_REF void ** RKL_GC_VOLATILE dictionariesScratchBuffer; RKL_STRONG_REF void ** RKL_GC_VOLATILE keysScratchBuffer; } RKLFindAll; typedef struct { CFStringRef string; CFHashCode hash; CFIndex length; RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniChar; } RKLBuffer; typedef struct { CFStringRef regexString; CFHashCode regexHash; RKLRegexOptions options; uregex *icu_regex; NSInteger captureCount; CFStringRef setToString; CFHashCode setToHash; CFIndex setToLength; NSUInteger setToIsImmutable:1; NSUInteger setToNeedsConversion:1; RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE setToUniChar; NSRange setToRange, lastFindRange, lastMatchRange; RKLBuffer *buffer; } RKLCachedRegex; //////////// #pragma mark - #pragma mark Translation unit scope global variables static RKLLRUCacheSet_t rkl_lruFixedBufferCacheSet = _RKL_LRU_CACHE_SET_INIT, rkl_lruDynamicBufferCacheSet = _RKL_LRU_CACHE_SET_INIT; static RKLBuffer rkl_lruDynamicBuffer[_RKL_LRU_CACHE_SET_WAYS]; static UniChar rkl_lruFixedUniChar[_RKL_LRU_CACHE_SET_WAYS][_RKL_FIXED_LENGTH]; // This is the fixed sized UTF-16 conversion buffer. static RKLBuffer rkl_lruFixedBuffer[_RKL_LRU_CACHE_SET_WAYS] = {{NULL, 0UL, 0L, &rkl_lruFixedUniChar[0][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[1][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[2][0]}, {NULL, 0UL, 0L, &rkl_lruFixedUniChar[3][0]}}; static RKLCachedRegex rkl_cachedRegexes[_RKL_REGEX_CACHE_LINES]; #if defined(__GNUC__) && (__GNUC__ == 4) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ == 2) static RKLCachedRegex * volatile rkl_lastCachedRegex; // XXX This is a work around for what appears to be a optimizer code generation bug in GCC 4.2. #else static RKLCachedRegex *rkl_lastCachedRegex; #endif // defined(__GNUC__) && (__GNUC__ == 4) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ == 2) static RKLLRUCacheSet_t rkl_cachedRegexCacheSets[_RKL_REGEX_LRU_CACHE_SETS] = { [0 ... (_RKL_REGEX_LRU_CACHE_SETS - 1UL)] = _RKL_LRU_CACHE_SET_INIT }; static RKLLookasideCache_t rkl_regexLookasideCache[_RKL_REGEX_LOOKASIDE_CACHE_SIZE] RKL_ALIGNED(64); static OSSpinLock rkl_cacheSpinLock = OS_SPINLOCK_INIT; static const UniChar rkl_emptyUniCharString[1]; // For safety, icu_regexes are 'set' to this when the string they were searched is cleared. static RKL_STRONG_REF void * RKL_GC_VOLATILE rkl_scratchBuffer[_RKL_SCRATCH_BUFFERS]; // Used to hold temporary allocations that are allocated via reallocf(). //////////// #pragma mark - #pragma mark CFArray and CFDictionary call backs // These are used when running under manual memory management for the array that rkl_splitArray creates. // The split strings are created, but not autoreleased. The (immutable) array is created using these callbacks, which skips the CFRetain() call, effectively transferring ownership to the CFArray object. // For each split string this saves the overhead of an autorelease, then an array retain, then an NSAutoreleasePool release. This is good for a ~30% speed increase. static void rkl_CFCallbackRelease(CFAllocatorRef allocator RKL_UNUSED_ARG, const void *ptr) { CFRelease((CFTypeRef)ptr); } static const CFArrayCallBacks rkl_transferOwnershipArrayCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual }; static const CFDictionaryKeyCallBacks rkl_transferOwnershipDictionaryKeyCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual, CFHash }; static const CFDictionaryValueCallBacks rkl_transferOwnershipDictionaryValueCallBacks = { (CFIndex)0L, NULL, rkl_CFCallbackRelease, CFCopyDescription, CFEqual }; #ifdef __OBJC_GC__ //////////// #pragma mark - #pragma mark Low-level Garbage Collection aware memory/resource allocation utilities // If compiled with Garbage Collection, we need to be able to do a few things slightly differently. // The basic premiss is that under GC we use a trampoline function pointer which is set to a _start function to catch the first invocation. // The _start function checks if GC is running and then overwrites the function pointer with the appropriate routine. Think of it as 'lazy linking'. enum { RKLScannedOption = NSScannedOption }; // rkl_collectingEnabled uses objc_getClass() to get the NSGarbageCollector class, which doesn't exist on earlier systems. // This allows for graceful failure should we find ourselves running on an earlier version of the OS without NSGarbageCollector. static BOOL rkl_collectingEnabled_first (void); static BOOL rkl_collectingEnabled_yes (void) { return(YES); } static BOOL rkl_collectingEnabled_no (void) { return(NO); } static BOOL(*rkl_collectingEnabled) (void) = rkl_collectingEnabled_first; static BOOL rkl_collectingEnabled_first (void) { BOOL gcEnabled = ([objc_getClass("NSGarbageCollector") defaultCollector] != NULL) ? YES : NO; if(gcEnabled == YES) { // This section of code is required due to what I consider to be a fundamental design flaw in Cocoas GC system. // Earlier versions of "Garbage Collection Programming Guide" stated that (paraphrased) "all globals are automatically roots". // Current versions of the guide now include the following warning: // "You may pass addresses of strong globals or statics into routines expecting pointers to object pointers (such as id* or NSError**) // only if they have first been assigned to directly, rather than through a pointer dereference." // This is a surprisingly non-trivial condition to actually meet in practice and is a recipe for impossible to debug race condition bugs. // We just happen to be very, very, very lucky in the fact that we can initialize our root set before the first use. NSUInteger x = 0UL; for(x = 0UL; x < _RKL_SCRATCH_BUFFERS; x++) { rkl_scratchBuffer[x] = NSAllocateCollectable(16UL, 0UL); rkl_scratchBuffer[x] = NULL; } for(x = 0UL; x < _RKL_LRU_CACHE_SET_WAYS; x++) { rkl_lruDynamicBuffer[x].uniChar = NSAllocateCollectable(16UL, 0UL); rkl_lruDynamicBuffer[x].uniChar = NULL; } } return((rkl_collectingEnabled = (gcEnabled == YES) ? rkl_collectingEnabled_yes : rkl_collectingEnabled_no)()); } // rkl_realloc() static void *rkl_realloc_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags); static void *rkl_realloc_std (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags RKL_UNUSED_ARG) { return((*ptr = reallocf(*ptr, size))); } static void *rkl_realloc_gc (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) { return((*ptr = NSReallocateCollectable(*ptr, (NSUInteger)size, flags))); } static void *(*rkl_realloc) (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(2,1) = rkl_realloc_first; static void *rkl_realloc_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr, size_t size, NSUInteger flags) { if(rkl_collectingEnabled()==YES) { rkl_realloc = rkl_realloc_gc; } else { rkl_realloc = rkl_realloc_std; } return(rkl_realloc(ptr, size, flags)); } // rkl_free() static void * rkl_free_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr); static void * rkl_free_std (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(*ptr != NULL) { free(*ptr); *ptr = NULL; } return(NULL); } static void * rkl_free_gc (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(*ptr != NULL) { *ptr = NULL; } return(NULL); } static void *(*rkl_free) (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) RKL_NONNULL_ARGS(1) = rkl_free_first; static void *rkl_free_first (RKL_STRONG_REF void ** RKL_GC_VOLATILE ptr) { if(rkl_collectingEnabled()==YES) { rkl_free = rkl_free_gc; } else { rkl_free = rkl_free_std; } return(rkl_free(ptr)); } // rkl_CFAutorelease() static id rkl_CFAutorelease_first (CFTypeRef obj); static id rkl_CFAutorelease_std (CFTypeRef obj) { return([(id)obj autorelease]); } static id rkl_CFAutorelease_gc (CFTypeRef obj) { return(NSMakeCollectable(obj)); } static id(*rkl_CFAutorelease) (CFTypeRef obj) = rkl_CFAutorelease_first; static id rkl_CFAutorelease_first (CFTypeRef obj) { return((rkl_CFAutorelease = (rkl_collectingEnabled()==YES) ? rkl_CFAutorelease_gc : rkl_CFAutorelease_std)(obj)); } // rkl_CreateStringWithSubstring() static id rkl_CreateStringWithSubstring_first (id string, NSRange range); static id rkl_CreateStringWithSubstring_std (id string, NSRange range) { return((id)CFStringCreateWithSubstring(NULL, (CFStringRef)string, CFMakeRange((CFIndex)range.location, (CFIndex)range.length))); } static id rkl_CreateStringWithSubstring_gc (id string, NSRange range) { return([string substringWithRange:range]); } static id(*rkl_CreateStringWithSubstring) (id string, NSRange range) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateStringWithSubstring_first; static id rkl_CreateStringWithSubstring_first (id string, NSRange range) { return((rkl_CreateStringWithSubstring = (rkl_collectingEnabled()==YES) ? rkl_CreateStringWithSubstring_gc : rkl_CreateStringWithSubstring_std)(string, range)); } // rkl_ReleaseObject() static id rkl_ReleaseObject_first (id obj); static id rkl_ReleaseObject_std (id obj) { CFRelease((CFTypeRef)obj); return(NULL); } static id rkl_ReleaseObject_gc (id obj RKL_UNUSED_ARG) { return(NULL); } static id (*rkl_ReleaseObject) (id obj) RKL_NONNULL_ARGS(1) = rkl_ReleaseObject_first; static id rkl_ReleaseObject_first (id obj) { return((rkl_ReleaseObject = (rkl_collectingEnabled()==YES) ? rkl_ReleaseObject_gc : rkl_ReleaseObject_std)(obj)); } // rkl_CreateArrayWithObjects() static id rkl_CreateArrayWithObjects_first (void **objects, NSUInteger count); static id rkl_CreateArrayWithObjects_std (void **objects, NSUInteger count) { return((id)CFArrayCreate(NULL, (const void **)objects, (CFIndex)count, &rkl_transferOwnershipArrayCallBacks)); } static id rkl_CreateArrayWithObjects_gc (void **objects, NSUInteger count) { return([NSArray arrayWithObjects:(const id *)objects count:count]); } static id(*rkl_CreateArrayWithObjects) (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateArrayWithObjects_first; static id rkl_CreateArrayWithObjects_first (void **objects, NSUInteger count) { return((rkl_CreateArrayWithObjects = (rkl_collectingEnabled()==YES) ? rkl_CreateArrayWithObjects_gc : rkl_CreateArrayWithObjects_std)(objects, count)); } // rkl_CreateAutoreleasedArray() static id rkl_CreateAutoreleasedArray_first (void **objects, NSUInteger count); static id rkl_CreateAutoreleasedArray_std (void **objects, NSUInteger count) { return((id)rkl_CFAutorelease(rkl_CreateArrayWithObjects(objects, count))); } static id rkl_CreateAutoreleasedArray_gc (void **objects, NSUInteger count) { return( rkl_CreateArrayWithObjects(objects, count) ); } static id(*rkl_CreateAutoreleasedArray) (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1) = rkl_CreateAutoreleasedArray_first; static id rkl_CreateAutoreleasedArray_first (void **objects, NSUInteger count) { return((rkl_CreateAutoreleasedArray = (rkl_collectingEnabled()==YES) ? rkl_CreateAutoreleasedArray_gc : rkl_CreateAutoreleasedArray_std)(objects, count)); } #else // __OBJC_GC__ not defined //////////// #pragma mark - #pragma mark Low-level explicit memory/resource allocation utilities enum { RKLScannedOption = 0 }; #define rkl_collectingEnabled() (NO) RKL_STATIC_INLINE void *rkl_realloc (void **ptr, size_t size, NSUInteger flags) RKL_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(2,1); RKL_STATIC_INLINE void *rkl_free (void **ptr) RKL_NONNULL_ARGS(1); RKL_STATIC_INLINE id rkl_CFAutorelease (CFTypeRef obj) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE id rkl_CreateAutoreleasedArray (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE id rkl_CreateArrayWithObjects (void **objects, NSUInteger count) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE id rkl_CreateStringWithSubstring (id string, NSRange range) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE id rkl_ReleaseObject (id obj) RKL_NONNULL_ARGS(1); RKL_STATIC_INLINE void *rkl_realloc (void **ptr, size_t size, NSUInteger flags RKL_UNUSED_ARG) { return((*ptr = reallocf(*ptr, size))); } RKL_STATIC_INLINE void *rkl_free (void **ptr) { if(*ptr != NULL) { free(*ptr); *ptr = NULL; } return(NULL); } RKL_STATIC_INLINE id rkl_CFAutorelease (CFTypeRef obj) { return([(id)obj autorelease]); } RKL_STATIC_INLINE id rkl_CreateArrayWithObjects (void **objects, NSUInteger count) { return((id)CFArrayCreate(NULL, (const void **)objects, (CFIndex)count, &rkl_transferOwnershipArrayCallBacks)); } RKL_STATIC_INLINE id rkl_CreateAutoreleasedArray (void **objects, NSUInteger count) { return(rkl_CFAutorelease(rkl_CreateArrayWithObjects(objects, count))); } RKL_STATIC_INLINE id rkl_CreateStringWithSubstring (id string, NSRange range) { return((id)CFStringCreateWithSubstring(NULL, (CFStringRef)string, CFMakeRange((CFIndex)range.location, (CFIndex)range.length))); } RKL_STATIC_INLINE id rkl_ReleaseObject (id obj) { CFRelease((CFTypeRef)obj); return(NULL); } #endif // __OBJC_GC__ //////////// #pragma mark - #pragma mark ICU function prototypes // ICU functions. See http://www.icu-project.org/apiref/icu4c/uregex_8h.html Tweaked slightly from the originals, but functionally identical. const char *RKL_ICU_FUNCTION_APPEND(u_errorName) ( int32_t status) RKL_WARN_UNUSED_PURE; int32_t RKL_ICU_FUNCTION_APPEND(u_strlen) (const UniChar *s) RKL_WARN_UNUSED_PURE_NONNULL_ARGS(1); int32_t RKL_ICU_FUNCTION_APPEND(uregex_appendReplacement) ( uregex *regexp, const UniChar *replacementText, int32_t replacementLength, UniChar **destBuf, int32_t *destCapacity, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,5,6); int32_t RKL_ICU_FUNCTION_APPEND(uregex_appendTail) ( uregex *regexp, UniChar **destBuf, int32_t *destCapacity, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,3,4); void RKL_ICU_FUNCTION_APPEND(uregex_close) ( uregex *regexp) RKL_NONNULL_ARGS(1); int32_t RKL_ICU_FUNCTION_APPEND(uregex_end) ( uregex *regexp, int32_t groupNum, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); BOOL RKL_ICU_FUNCTION_APPEND(uregex_find) ( uregex *regexp, int32_t location, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); BOOL RKL_ICU_FUNCTION_APPEND(uregex_findNext) ( uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); int32_t RKL_ICU_FUNCTION_APPEND(uregex_groupCount) ( uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); uregex *RKL_ICU_FUNCTION_APPEND(uregex_open) (const UniChar *pattern, int32_t patternLength, RKLRegexOptions flags, UParseError *parseError, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,4,5); void RKL_ICU_FUNCTION_APPEND(uregex_reset) ( uregex *regexp, int32_t newIndex, int32_t *status) RKL_NONNULL_ARGS(1,3); void RKL_ICU_FUNCTION_APPEND(uregex_setText) ( uregex *regexp, const UniChar *text, int32_t textLength, int32_t *status) RKL_NONNULL_ARGS(1,2,4); int32_t RKL_ICU_FUNCTION_APPEND(uregex_start) ( uregex *regexp, int32_t groupNum, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3); uregex *RKL_ICU_FUNCTION_APPEND(uregex_clone) (const uregex *regexp, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2); //////////// #pragma mark - #pragma mark RegexKitLite internal, private function prototypes // Functions used for managing the 4-way set associative LRU cache and regex string hash lookaside cache. RKL_STATIC_INLINE NSUInteger rkl_leastRecentlyUsedWayInSet ( NSUInteger cacheSetsCount, const RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set) RKL_WARN_UNUSED_NONNULL_ARGS(2); RKL_STATIC_INLINE void rkl_accessCacheSetWay ( NSUInteger cacheSetsCount, RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set, NSUInteger way) RKL_NONNULL_ARGS(2); RKL_STATIC_INLINE NSUInteger rkl_regexLookasideCacheIndexForPointerAndOptions (const void *ptr, RKLRegexOptions options) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE void rkl_setRegexLookasideCacheToCachedRegexForPointer (const RKLCachedRegex *cachedRegex, const void *ptr) RKL_NONNULL_ARGS(1,2); RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexFromRegexLookasideCacheForString (const void *ptr, RKLRegexOptions options) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE NSUInteger rkl_makeCacheSetHash ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; RKL_STATIC_INLINE NSUInteger rkl_cacheSetForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; RKL_STATIC_INLINE NSUInteger rkl_cacheWayForCachedRegex (const RKLCachedRegex *cachedRegex) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE NSUInteger rkl_cacheSetForCachedRegex (const RKLCachedRegex *cachedRegex) RKL_WARN_UNUSED_NONNULL_ARGS(1); RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForCacheSetAndWay ( NSUInteger cacheSet, NSUInteger cacheWay) RKL_WARN_UNUSED; RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForRegexHashAndOptionsAndWay ( CFHashCode regexHash, RKLRegexOptions options, NSUInteger cacheWay) RKL_WARN_UNUSED; RKL_STATIC_INLINE void rkl_updateCachesWithCachedRegex ( RKLCachedRegex *cachedRegex, const void *ptr, int hitOrMiss RKL_UNUSED_DTRACE_ARG, int status RKL_UNUSED_DTRACE_ARG) RKL_NONNULL_ARGS(1,2); RKL_STATIC_INLINE RKLCachedRegex *rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) RKL_WARN_UNUSED; static RKLCachedRegex *rkl_getCachedRegex (NSString *regexString, RKLRegexOptions options, NSError **error, id *exception) RKL_WARN_UNUSED_NONNULL_ARGS(1,4); static NSUInteger rkl_setCachedRegexToString (RKLCachedRegex *cachedRegex, const NSRange *range, int32_t *status, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,3,4); static RKLCachedRegex *rkl_getCachedRegexSetToString (NSString *regexString, RKLRegexOptions options, NSString *matchString, NSUInteger *matchLengthPtr, NSRange *matchRange, NSError **error, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4,5,7,8); static id rkl_performDictionaryVarArgsOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, id firstKey, va_list varArgsList) RKL_NONNULL_ARGS(1,2); static id rkl_performRegexOp (id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount]) RKL_NONNULL_ARGS(1,2); static void rkl_handleDelayedAssert (id self, SEL _cmd, id exception) RKL_NONNULL_ARGS(3); static NSUInteger rkl_search (RKLCachedRegex *cachedRegex, NSRange *searchRange, NSUInteger updateSearchRange, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,5); static BOOL rkl_findRanges (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4,5); static NSUInteger rkl_growFindRanges (RKLCachedRegex *cachedRegex, NSUInteger lastLocation, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4); static NSArray *rkl_makeArray (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,4); static id rkl_makeDictionary (RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount], id *exception RKL_UNUSED_ASSERTION_ARG) RKL_WARN_UNUSED_NONNULL_ARGS(1,3,5,6); static NSString *rkl_replaceString (RKLCachedRegex *cachedRegex, id searchString, NSUInteger searchU16Length, NSString *replacementString, NSUInteger replacementU16Length, NSInteger *replacedCount, NSUInteger replaceMutable, id *exception, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,8,9); static int32_t rkl_replaceAll (RKLCachedRegex *cachedRegex, RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar, int32_t replacementU16Length, UniChar *replacedUniChar, int32_t replacedU16Capacity, NSInteger *replacedCount, int32_t *needU16Capacity, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4,6,7,8,9); static NSUInteger rkl_isRegexValid (id self, SEL _cmd, NSString *regex, RKLRegexOptions options, NSInteger *captureCountPtr, NSError **error) RKL_NONNULL_ARGS(1,2); static void rkl_clearStringCache (void); static void rkl_clearBuffer (RKLBuffer *buffer, NSUInteger freeDynamicBuffer) RKL_NONNULL_ARGS(1); static void rkl_clearCachedRegex (RKLCachedRegex *cachedRegex) RKL_NONNULL_ARGS(1); static void rkl_clearCachedRegexSetTo (RKLCachedRegex *cachedRegex) RKL_NONNULL_ARGS(1); static NSDictionary *rkl_userInfoDictionary (RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, ...) RKL_WARN_UNUSED_SENTINEL; static NSError *rkl_makeNSError (RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, NSString *errorDescription) RKL_WARN_UNUSED; static NSException *rkl_NSExceptionForRegex (NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status) RKL_WARN_UNUSED_NONNULL_ARGS(1); static NSDictionary *rkl_makeAssertDictionary (const char *function, const char *file, int line, NSString *format, ...) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4); static NSString *rkl_stringFromClassAndMethod (id object, SEL selector, NSString *format, ...) RKL_WARN_UNUSED_NONNULL_ARGS(3); RKL_STATIC_INLINE int32_t rkl_getRangeForCapture(RKLCachedRegex *cr, int32_t *s, int32_t c, NSRange *r) RKL_WARN_UNUSED_NONNULL_ARGS(1,2,4); RKL_STATIC_INLINE int32_t rkl_getRangeForCapture(RKLCachedRegex *cr, int32_t *s, int32_t c, NSRange *r) { uregex *re = cr->icu_regex; int32_t start = RKL_ICU_FUNCTION_APPEND(uregex_start)(re, c, s); if(RKL_EXPECTED((*s > U_ZERO_ERROR), 0L) || (start == -1)) { *r = NSNotFoundRange; } else { r->location = (NSUInteger)start; r->length = (NSUInteger)RKL_ICU_FUNCTION_APPEND(uregex_end)(re, c, s) - r->location; r->location += cr->setToRange.location; } return(*s); } RKL_STATIC_INLINE RKLFindAll rkl_makeFindAll(RKL_STRONG_REF NSRange * RKL_GC_VOLATILE r, NSRange fir, NSInteger c, size_t s, size_t su, RKL_STRONG_REF void ** RKL_GC_VOLATILE rsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ssb, RKL_STRONG_REF void ** RKL_GC_VOLATILE asb, RKL_STRONG_REF void ** RKL_GC_VOLATILE dsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ksb, NSInteger f, NSInteger cap, NSInteger fut) RKL_WARN_UNUSED_CONST; RKL_STATIC_INLINE RKLFindAll rkl_makeFindAll(RKL_STRONG_REF NSRange * RKL_GC_VOLATILE r, NSRange fir, NSInteger c, size_t s, size_t su, RKL_STRONG_REF void ** RKL_GC_VOLATILE rsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ssb, RKL_STRONG_REF void ** RKL_GC_VOLATILE asb, RKL_STRONG_REF void ** RKL_GC_VOLATILE dsb, RKL_STRONG_REF void ** RKL_GC_VOLATILE ksb, NSInteger f, NSInteger cap, NSInteger fut) { return(((RKLFindAll){ .ranges=r, .findInRange=fir, .remainingRange=fir, .capacity=c, .found=f, .findUpTo=fut, .capture=cap, .addedSplitRanges=0L, .size=s, .stackUsed=su, .rangesScratchBuffer=rsb, .stringsScratchBuffer=ssb, .arraysScratchBuffer=asb, .dictionariesScratchBuffer=dsb, .keysScratchBuffer=ksb})); } //////////// #pragma mark - #pragma mark RKL_FAST_MUTABLE_CHECK implementation #ifdef RKL_FAST_MUTABLE_CHECK // We use a trampoline function pointer to check at run time if the function __CFStringIsMutable is available. // If it is, the trampoline function pointer is replaced with the address of that function. // Otherwise, we assume the worst case that every string is mutable. // This hopefully helps to protect us since we're using an undocumented, non-public API call. // We will keep on working if it ever does go away, just with a bit less performance due to the overhead of mutable checks. static BOOL rkl_CFStringIsMutable_first (CFStringRef str); static BOOL rkl_CFStringIsMutable_yes (CFStringRef str RKL_UNUSED_ARG) { return(YES); } static BOOL(*rkl_CFStringIsMutable) (CFStringRef str) = rkl_CFStringIsMutable_first; static BOOL rkl_CFStringIsMutable_first (CFStringRef str) { if((rkl_CFStringIsMutable = (BOOL(*)(CFStringRef))dlsym(RTLD_DEFAULT, "__CFStringIsMutable")) == NULL) { rkl_CFStringIsMutable = rkl_CFStringIsMutable_yes; } return(rkl_CFStringIsMutable(str)); } #else // RKL_FAST_MUTABLE_CHECK is not defined. Assume that all strings are potentially mutable. #define rkl_CFStringIsMutable(s) (YES) #endif // RKL_FAST_MUTABLE_CHECK //////////// #pragma mark - #pragma mark iPhone / iPod touch low memory notification handler #if defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) && (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS == 1) // The next few lines are specifically for the iPhone to catch low memory conditions. // The basic idea is that rkl_RegisterForLowMemoryNotifications() is set to be run once by the linker at load time via __attribute((constructor)). // rkl_RegisterForLowMemoryNotifications() tries to find the iPhone low memory notification symbol. If it can find it, // it registers with the default NSNotificationCenter to call the RKLLowMemoryWarningObserver class method +lowMemoryWarning:. // rkl_RegisterForLowMemoryNotifications() uses an atomic compare and swap to guarantee that it initializes exactly once. // +lowMemoryWarning tries to acquire the cache lock. If it gets the lock, it clears the cache. If it can't, it calls performSelector: // with a delay of half a second to try again. This will hopefully prevent any deadlocks, such as a RegexKitLite request for // memory triggering a notification while the lock is held. static void rkl_RegisterForLowMemoryNotifications(void) RKL_ATTRIBUTES(used); @interface RKLLowMemoryWarningObserver : NSObject +(void)lowMemoryWarning:(id)notification; @end @implementation RKLLowMemoryWarningObserver +(void)lowMemoryWarning:(id)notification { if(OSSpinLockTry(&rkl_cacheSpinLock)) { rkl_clearStringCache(); OSSpinLockUnlock(&rkl_cacheSpinLock); } else { [[RKLLowMemoryWarningObserver class] performSelector:@selector(lowMemoryWarning:) withObject:notification afterDelay:(NSTimeInterval)0.1]; } } @end static volatile int rkl_HaveRegisteredForLowMemoryNotifications = 0; __attribute__((constructor)) static void rkl_RegisterForLowMemoryNotifications(void) { _Bool didSwap = false; void **memoryWarningNotification = NULL; while((rkl_HaveRegisteredForLowMemoryNotifications == 0) && ((didSwap = OSAtomicCompareAndSwapIntBarrier(0, 1, &rkl_HaveRegisteredForLowMemoryNotifications)) == false)) { /* Allows for spurious CAS failures. */ } if(didSwap == true) { if((memoryWarningNotification = (void **)dlsym(RTLD_DEFAULT, "UIApplicationDidReceiveMemoryWarningNotification")) != NULL) { [[NSNotificationCenter defaultCenter] addObserver:[RKLLowMemoryWarningObserver class] selector:@selector(lowMemoryWarning:) name:(NSString *)*memoryWarningNotification object:NULL]; } } } #endif // defined(RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS) && (RKL_REGISTER_FOR_IPHONE_LOWMEM_NOTIFICATIONS == 1) //////////// #pragma mark - #pragma mark DTrace functionality #ifdef _RKL_DTRACE_ENABLED // compiledRegexCache(unsigned long eventID, const char *regexUTF8, int options, int captures, int hitMiss, int icuStatusCode, const char *icuErrorMessage, double *hitRate); // utf16ConversionCache(unsigned long eventID, unsigned int lookupResultFlags, double *hitRate, const void *string, unsigned long NSRange.location, unsigned long NSRange.length, long length); /* provider RegexKitLite { probe compiledRegexCache(unsigned long, const char *, unsigned int, int, int, int, const char *, double *); probe utf16ConversionCache(unsigned long, unsigned int, double *, const void *, unsigned long, unsigned long, long); }; #pragma D attributes Unstable/Unstable/Common provider RegexKitLite provider #pragma D attributes Private/Private/Common provider RegexKitLite module #pragma D attributes Private/Private/Common provider RegexKitLite function #pragma D attributes Unstable/Unstable/Common provider RegexKitLite name #pragma D attributes Unstable/Unstable/Common provider RegexKitLite args */ #define REGEXKITLITE_STABILITY "___dtrace_stability$RegexKitLite$v1$4_4_5_1_1_5_1_1_5_4_4_5_4_4_5" #define REGEXKITLITE_TYPEDEFS "___dtrace_typedefs$RegexKitLite$v1" #define REGEXKITLITE_COMPILEDREGEXCACHE(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { __asm__ volatile(".reference " REGEXKITLITE_TYPEDEFS); __dtrace_probe$RegexKitLite$compiledRegexCache$v1$756e7369676e6564206c6f6e67$63686172202a$756e7369676e656420696e74$696e74$696e74$696e74$63686172202a$646f75626c65202a(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); __asm__ volatile(".reference " REGEXKITLITE_STABILITY); } #define REGEXKITLITE_COMPILEDREGEXCACHE_ENABLED() __dtrace_isenabled$RegexKitLite$compiledRegexCache$v1() #define REGEXKITLITE_CONVERTEDSTRINGU16CACHE(arg0, arg1, arg2, arg3, arg4, arg5, arg6) { __asm__ volatile(".reference " REGEXKITLITE_TYPEDEFS); __dtrace_probe$RegexKitLite$utf16ConversionCache$v1$756e7369676e6564206c6f6e67$756e7369676e656420696e74$646f75626c65202a$766f6964202a$756e7369676e6564206c6f6e67$756e7369676e6564206c6f6e67$6c6f6e67(arg0, arg1, arg2, arg3, arg4, arg5, arg6); __asm__ volatile(".reference " REGEXKITLITE_STABILITY); } #define REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED() __dtrace_isenabled$RegexKitLite$utf16ConversionCache$v1() extern void __dtrace_probe$RegexKitLite$compiledRegexCache$v1$756e7369676e6564206c6f6e67$63686172202a$756e7369676e656420696e74$696e74$696e74$696e74$63686172202a$646f75626c65202a(unsigned long, const char *, unsigned int, int, int, int, const char *, double *); extern int __dtrace_isenabled$RegexKitLite$compiledRegexCache$v1(void); extern void __dtrace_probe$RegexKitLite$utf16ConversionCache$v1$756e7369676e6564206c6f6e67$756e7369676e656420696e74$646f75626c65202a$766f6964202a$756e7369676e6564206c6f6e67$756e7369676e6564206c6f6e67$6c6f6e67(unsigned long, unsigned int, double *, const void *, unsigned long, unsigned long, long); extern int __dtrace_isenabled$RegexKitLite$utf16ConversionCache$v1(void); //////////////////////////// enum { RKLCacheHitLookupFlag = 1 << 0, RKLConversionRequiredLookupFlag = 1 << 1, RKLSetTextLookupFlag = 1 << 2, RKLDynamicBufferLookupFlag = 1 << 3, RKLErrorLookupFlag = 1 << 4, RKLEnumerationBufferLookupFlag = 1 << 5, }; #define rkl_dtrace_addLookupFlag(a,b) do { a |= (unsigned int)(b); } while(0) static char rkl_dtrace_regexUTF8[_RKL_REGEX_CACHE_LINES + 1UL][_RKL_DTRACE_REGEXUTF8_SIZE]; static NSUInteger rkl_dtrace_eventID, rkl_dtrace_compiledCacheLookups, rkl_dtrace_compiledCacheHits, rkl_dtrace_conversionBufferLookups, rkl_dtrace_conversionBufferHits; #define rkl_dtrace_incrementEventID() do { rkl_dtrace_eventID++; } while(0) #define rkl_dtrace_incrementAndGetEventID(v) do { rkl_dtrace_eventID++; v = rkl_dtrace_eventID; } while(0) #define rkl_dtrace_compiledRegexCache(a0, a1, a2, a3, a4, a5) do { int _a3 = (a3); rkl_dtrace_compiledCacheLookups++; if(_a3 == 1) { rkl_dtrace_compiledCacheHits++; } if(RKL_EXPECTED(REGEXKITLITE_COMPILEDREGEXCACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_compiledCacheLookups > 0UL) { hitRate = ((double)rkl_dtrace_compiledCacheHits / (double)rkl_dtrace_compiledCacheLookups) * 100.0; } REGEXKITLITE_COMPILEDREGEXCACHE(rkl_dtrace_eventID, a0, a1, a2, _a3, a4, a5, &hitRate); } } while(0) #define rkl_dtrace_utf16ConversionCache(a0, a1, a2, a3, a4) do { unsigned int _a0 = (a0); if((_a0 & RKLConversionRequiredLookupFlag) != 0U) { rkl_dtrace_conversionBufferLookups++; if((_a0 & RKLCacheHitLookupFlag) != 0U) { rkl_dtrace_conversionBufferHits++; } } if(RKL_EXPECTED(REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_conversionBufferLookups > 0UL) { hitRate = ((double)rkl_dtrace_conversionBufferHits / (double)rkl_dtrace_conversionBufferLookups) * 100.0; } REGEXKITLITE_CONVERTEDSTRINGU16CACHE(rkl_dtrace_eventID, _a0, &hitRate, a1, a2, a3, a4); } } while(0) #define rkl_dtrace_utf16ConversionCacheWithEventID(c0, a0, a1, a2, a3, a4) do { unsigned int _a0 = (a0); if((_a0 & RKLConversionRequiredLookupFlag) != 0U) { rkl_dtrace_conversionBufferLookups++; if((_a0 & RKLCacheHitLookupFlag) != 0U) { rkl_dtrace_conversionBufferHits++; } } if(RKL_EXPECTED(REGEXKITLITE_CONVERTEDSTRINGU16CACHE_ENABLED(), 0L)) { double hitRate = 0.0; if(rkl_dtrace_conversionBufferLookups > 0UL) { hitRate = ((double)rkl_dtrace_conversionBufferHits / (double)rkl_dtrace_conversionBufferLookups) * 100.0; } REGEXKITLITE_CONVERTEDSTRINGU16CACHE(c0, _a0, &hitRate, a1, a2, a3, a4); } } while(0) // \342\200\246 == UTF8 for HORIZONTAL ELLIPSIS, aka triple dots '...' #define RKL_UTF8_ELLIPSE "\342\200\246" // rkl_dtrace_getRegexUTF8 will copy the str argument to utf8Buffer using UTF8 as the string encoding. // If the utf8 encoding would take up more bytes than the utf8Buffers length, then the unicode character 'HORIZONTAL ELLIPSIS' ('...') is appended to indicate truncation occurred. static void rkl_dtrace_getRegexUTF8(CFStringRef str, char *utf8Buffer) RKL_NONNULL_ARGS(2); static void rkl_dtrace_getRegexUTF8(CFStringRef str, char *utf8Buffer) { if((str == NULL) || (utf8Buffer == NULL)) { return; } CFIndex maxLength = ((CFIndex)_RKL_DTRACE_REGEXUTF8_SIZE - 2L), maxBytes = (maxLength - (CFIndex)sizeof(RKL_UTF8_ELLIPSE) - 1L), stringU16Length = CFStringGetLength(str), usedBytes = 0L; CFStringGetBytes(str, CFMakeRange(0L, ((stringU16Length < maxLength) ? stringU16Length : maxLength)), kCFStringEncodingUTF8, (UInt8)'?', (Boolean)0, (UInt8 *)utf8Buffer, maxBytes, &usedBytes); if(usedBytes == maxBytes) { strncpy(utf8Buffer + usedBytes, RKL_UTF8_ELLIPSE, ((size_t)_RKL_DTRACE_REGEXUTF8_SIZE - (size_t)usedBytes) - 2UL); } else { utf8Buffer[usedBytes] = (char)0; } } #else // _RKL_DTRACE_ENABLED #define rkl_dtrace_incrementEventID() #define rkl_dtrace_incrementAndGetEventID(v) #define rkl_dtrace_compiledRegexCache(a0, a1, a2, a3, a4, a5) #define rkl_dtrace_utf16ConversionCache(a0, a1, a2, a3, a4) #define rkl_dtrace_utf16ConversionCacheWithEventID(c0, a0, a1, a2, a3, a4) #define rkl_dtrace_getRegexUTF8(str, buf) #define rkl_dtrace_addLookupFlag(a,b) #endif // _RKL_DTRACE_ENABLED //////////// #pragma mark - #pragma mark RegexKitLite low-level internal functions #pragma mark - // The 4-way set associative LRU logic comes from Henry S. Warren Jr.'s Hacker's Delight, "revisions", 7-7 An LRU Algorithm: // http://www.hackersdelight.org/revisions.pdf // The functions rkl_leastRecentlyUsedWayInSet() and rkl_accessCacheSetWay() implement the cache functionality and are used // from a number of different places that need to perform caching (i.e., cached regex, cached UTF16 conversions, etc) #pragma mark 4-way set associative LRU functions RKL_STATIC_INLINE NSUInteger rkl_leastRecentlyUsedWayInSet(NSUInteger cacheSetsCount, const RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger set) { RKLCAbortAssert((cacheSetsArray != NULL) && ((NSInteger)cacheSetsCount > 0L) && (set < cacheSetsCount) && ((cacheSetsArray == rkl_cachedRegexCacheSets) ? set < _RKL_REGEX_LRU_CACHE_SETS : 1) && (((sizeof(unsigned int) - sizeof(RKLLRUCacheSet_t)) * 8) < (sizeof(unsigned int) * 8))); unsigned int cacheSet = (((unsigned int)cacheSetsArray[set]) << ((sizeof(unsigned int) - sizeof(RKLLRUCacheSet_t)) * 8)); // __builtin_clz takes an 'unsigned int' argument. The rest is to ensure bit alignment regardless of 32/64/whatever. NSUInteger leastRecentlyUsed = ((NSUInteger)(3LU - (NSUInteger)((__builtin_clz((~(((cacheSet & 0x77777777U) + 0x77777777U) | cacheSet | 0x77777777U))) ) >> 2))); RKLCAbortAssert(leastRecentlyUsed < _RKL_LRU_CACHE_SET_WAYS); return(leastRecentlyUsed); } RKL_STATIC_INLINE void rkl_accessCacheSetWay(NSUInteger cacheSetsCount, RKLLRUCacheSet_t cacheSetsArray[cacheSetsCount], NSUInteger cacheSet, NSUInteger cacheWay) { RKLCAbortAssert((cacheSetsArray != NULL) && ((NSInteger)cacheSetsCount > 0L) && (cacheSet < cacheSetsCount) && (cacheWay < _RKL_LRU_CACHE_SET_WAYS) && ((cacheSetsArray == rkl_cachedRegexCacheSets) ? cacheSet < _RKL_REGEX_LRU_CACHE_SETS : 1)); cacheSetsArray[cacheSet] = (RKLLRUCacheSet_t)(((cacheSetsArray[cacheSet] & (RKLLRUCacheSet_t)0xFFFFU) | (((RKLLRUCacheSet_t)0xFU) << (cacheWay * 4U))) & (~(((RKLLRUCacheSet_t)0x1111U) << (3U - cacheWay)))); } #pragma mark Common, macro'ish compiled regular expression cache logic // These functions consolidate bits and pieces of code used to maintain, update, and access the 4-way set associative LRU cache and Regex Lookaside Cache. RKL_STATIC_INLINE NSUInteger rkl_regexLookasideCacheIndexForPointerAndOptions (const void *ptr, RKLRegexOptions options) { return(((((NSUInteger)(ptr)) >> 4) + options + (options >> 4)) & _RKL_REGEX_LOOKASIDE_CACHE_MASK); } RKL_STATIC_INLINE void rkl_setRegexLookasideCacheToCachedRegexForPointer (const RKLCachedRegex *cachedRegex, const void *ptr) { rkl_regexLookasideCache[rkl_regexLookasideCacheIndexForPointerAndOptions(ptr, cachedRegex->options)] = (cachedRegex - rkl_cachedRegexes); } RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexFromRegexLookasideCacheForString (const void *ptr, RKLRegexOptions options) { return(&rkl_cachedRegexes[rkl_regexLookasideCache[rkl_regexLookasideCacheIndexForPointerAndOptions(ptr, options)]]); } RKL_STATIC_INLINE NSUInteger rkl_makeCacheSetHash ( CFHashCode regexHash, RKLRegexOptions options) { return((NSUInteger)regexHash ^ (NSUInteger)options); } RKL_STATIC_INLINE NSUInteger rkl_cacheSetForRegexHashAndOptions ( CFHashCode regexHash, RKLRegexOptions options) { return((rkl_makeCacheSetHash(regexHash, options) % _RKL_REGEX_LRU_CACHE_SETS)); } RKL_STATIC_INLINE NSUInteger rkl_cacheWayForCachedRegex (const RKLCachedRegex *cachedRegex) { return((cachedRegex - rkl_cachedRegexes) % _RKL_LRU_CACHE_SET_WAYS); } RKL_STATIC_INLINE NSUInteger rkl_cacheSetForCachedRegex (const RKLCachedRegex *cachedRegex) { return(rkl_cacheSetForRegexHashAndOptions(cachedRegex->regexHash, cachedRegex->options)); } RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForCacheSetAndWay ( NSUInteger cacheSet, NSUInteger cacheWay) { return(&rkl_cachedRegexes[((cacheSet * _RKL_LRU_CACHE_SET_WAYS) + cacheWay)]); } RKL_STATIC_INLINE RKLCachedRegex *rkl_cachedRegexForRegexHashAndOptionsAndWay ( CFHashCode regexHash, RKLRegexOptions options, NSUInteger cacheWay) { return(rkl_cachedRegexForCacheSetAndWay(rkl_cacheSetForRegexHashAndOptions(regexHash, options), cacheWay)); } RKL_STATIC_INLINE void rkl_updateCachesWithCachedRegex(RKLCachedRegex *cachedRegex, const void *ptr, int hitOrMiss RKL_UNUSED_DTRACE_ARG, int status RKL_UNUSED_DTRACE_ARG) { rkl_lastCachedRegex = cachedRegex; rkl_setRegexLookasideCacheToCachedRegexForPointer(cachedRegex, ptr); rkl_accessCacheSetWay(_RKL_REGEX_LRU_CACHE_SETS, rkl_cachedRegexCacheSets, rkl_cacheSetForCachedRegex(cachedRegex), rkl_cacheWayForCachedRegex(cachedRegex)); // Set the matching line as the most recently used. rkl_dtrace_compiledRegexCache(&rkl_dtrace_regexUTF8[(cachedRegex - rkl_cachedRegexes)][0], cachedRegex->options, (int)cachedRegex->captureCount, hitOrMiss, status, NULL); } RKL_STATIC_INLINE RKLCachedRegex *rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions(CFHashCode regexHash, RKLRegexOptions options) { NSUInteger cacheSet = rkl_cacheSetForRegexHashAndOptions(regexHash, options); return(rkl_cachedRegexForCacheSetAndWay(cacheSet, rkl_leastRecentlyUsedWayInSet(_RKL_REGEX_LRU_CACHE_SETS, rkl_cachedRegexCacheSets, cacheSet))); } #pragma mark Regular expression lookup function // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! // ---------- static RKLCachedRegex *rkl_getCachedRegex(NSString *regexString, RKLRegexOptions options, NSError **error, id *exception) { // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv RKLCachedRegex *cachedRegex = NULL; CFHashCode regexHash = 0UL; int32_t status = 0; RKLCDelayedAssert((rkl_cacheSpinLock != (OSSpinLock)0) && (regexString != NULL), exception, exitNow); // Fast path the common case where this regex is exactly the same one used last time. // The pointer equality test is valid under these circumstances since the cachedRegex->regexString is an immutable copy. // If the regexString argument is mutable, this test will fail, and we'll use the the slow path cache check below. if(RKL_EXPECTED(rkl_lastCachedRegex != NULL, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->regexString == (CFStringRef)regexString, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->options == options, 1L) && RKL_EXPECTED(rkl_lastCachedRegex->icu_regex != NULL, 1L)) { rkl_dtrace_compiledRegexCache(&rkl_dtrace_regexUTF8[(rkl_lastCachedRegex - rkl_cachedRegexes)][0], rkl_lastCachedRegex->options, (int)rkl_lastCachedRegex->captureCount, 1, 0, NULL); return(rkl_lastCachedRegex); } rkl_lastCachedRegex = NULL; // Make sure that rkl_lastCachedRegex is NULL in case there is some kind of error. cachedRegex = rkl_cachedRegexFromRegexLookasideCacheForString(regexString, options); // Check the Regex Lookaside Cache to see if we can quickly find the correct Cached Regex for this regexString pointer + options. if((RKL_EXPECTED(cachedRegex->regexString == (CFStringRef)regexString, 1L) || (RKL_EXPECTED(cachedRegex->regexString != NULL, 1L) && RKL_EXPECTED(CFEqual((CFTypeRef)regexString, (CFTypeRef)cachedRegex->regexString) == YES, 1L))) && RKL_EXPECTED(cachedRegex->options == options, 1L) && RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { goto foundMatch; } // There was a Regex Lookaside Cache hit, jump to foundMatch: to quickly return the result. A Regex Lookaside Cache hit allows us to bypass calling CFHash(), which is a decent performance win. else { cachedRegex = NULL; regexHash = CFHash((CFTypeRef)regexString); } // Regex Lookaside Cache miss. We need to call CFHash() to determine the cache set for this regex. NSInteger cacheWay = 0L; // Check each way of the set that this regex belongs to. for(cacheWay = ((NSInteger)_RKL_LRU_CACHE_SET_WAYS - 1L); cacheWay > 0L; cacheWay--) { // Checking the ways in reverse (3, 2, 1, 0) finds a match "sooner" on average. cachedRegex = rkl_cachedRegexForRegexHashAndOptionsAndWay(regexHash, options, (NSUInteger)cacheWay); // Return the cached entry if it's a match. If regexString is mutable, the pointer equality test will fail, and CFEqual() is used to determine true equality with the immutable cachedRegex copy. CFEqual() performs a slow character by character check. if(RKL_EXPECTED(cachedRegex->regexHash == regexHash, 0UL) && ((cachedRegex->regexString == (CFStringRef)regexString) || (RKL_EXPECTED(cachedRegex->regexString != NULL, 1L) && RKL_EXPECTED(CFEqual((CFTypeRef)regexString, (CFTypeRef)cachedRegex->regexString) == YES, 1L))) && RKL_EXPECTED(cachedRegex->options == options, 1L) && RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { foundMatch: // Control can transfer here (from above) via a Regex Lookaside Cache hit. rkl_updateCachesWithCachedRegex(cachedRegex, regexString, 1, 0); return(cachedRegex); } } // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Code below this point is not as sensitive to speed since compiling a regular expression is an extremely expensive operation. // The regex was not found in the cache. Get the cached regex for the least recently used line in the set, then clear the cached regex and create a new ICU regex in its place. cachedRegex = rkl_leastRecentlyUsedCachedRegexForRegexHashAndOptions(regexHash, options); rkl_clearCachedRegex(cachedRegex); if(RKL_EXPECTED((cachedRegex->regexString = CFStringCreateCopy(NULL, (CFStringRef)regexString)) == NULL, 0L)) { goto exitNow; } ; // Get a cheap immutable copy. rkl_dtrace_getRegexUTF8(cachedRegex->regexString, &rkl_dtrace_regexUTF8[(cachedRegex - rkl_cachedRegexes)][0]); cachedRegex->regexHash = regexHash; cachedRegex->options = options; CFIndex regexStringU16Length = CFStringGetLength(cachedRegex->regexString); // In UTF16 code units. UParseError parseError = (UParseError){-1, -1, {0}, {0}}; RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE regexUniChar = NULL; if(RKL_EXPECTED(regexStringU16Length >= (CFIndex)INT_MAX, 0L)) { *exception = [NSException exceptionWithName:NSRangeException reason:@"Regex string length exceeds INT_MAX" userInfo:NULL]; goto exitNow; } // Try to quickly obtain regexString in UTF16 format. if((regexUniChar = CFStringGetCharactersPtr(cachedRegex->regexString)) == NULL) { // We didn't get the UTF16 pointer quickly and need to perform a full conversion in a temp buffer. RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniCharBuffer = NULL; if(((size_t)regexStringU16Length * sizeof(UniChar)) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca( (size_t)regexStringU16Length * sizeof(UniChar) )) == NULL, 0L)) { goto exitNow; } } // Try to use the stack. else { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], (size_t)regexStringU16Length * sizeof(UniChar), 0UL)) == NULL, 0L)) { goto exitNow; } } // Otherwise use the heap. CFStringGetCharacters(cachedRegex->regexString, CFMakeRange(0L, regexStringU16Length), uniCharBuffer); // Convert regexString to UTF16. regexUniChar = uniCharBuffer; } // Create the ICU regex. if(RKL_EXPECTED((cachedRegex->icu_regex = RKL_ICU_FUNCTION_APPEND(uregex_open)(regexUniChar, (int32_t)regexStringU16Length, options, &parseError, &status)) == NULL, 0L)) { goto exitNow; } if(RKL_EXPECTED(status <= U_ZERO_ERROR, 1L)) { cachedRegex->captureCount = (NSInteger)RKL_ICU_FUNCTION_APPEND(uregex_groupCount)(cachedRegex->icu_regex, &status); } if(RKL_EXPECTED(status <= U_ZERO_ERROR, 1L)) { rkl_updateCachesWithCachedRegex(cachedRegex, regexString, 0, status); } exitNow: if(RKL_EXPECTED(rkl_scratchBuffer[0] != NULL, 0L)) { rkl_scratchBuffer[0] = rkl_free(&rkl_scratchBuffer[0]); } if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L)) { rkl_clearCachedRegex(cachedRegex); cachedRegex = rkl_lastCachedRegex = NULL; if(error != NULL) { *error = rkl_makeNSError((RKLUserInfoOptions)RKLUserInfoNone, regexString, options, &parseError, status, NULL, NSNotFoundRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"There was an error compiling the regular expression."); } } #ifdef _RKL_DTRACE_ENABLED if(RKL_EXPECTED(cachedRegex == NULL, 1L)) { char regexUTF8[_RKL_DTRACE_REGEXUTF8_SIZE]; const char *err = NULL; if(status != U_ZERO_ERROR) { err = RKL_ICU_FUNCTION_APPEND(u_errorName)(status); } rkl_dtrace_getRegexUTF8((CFStringRef)regexString, regexUTF8); rkl_dtrace_compiledRegexCache(regexUTF8, options, -1, -1, status, err); } #endif // _RKL_DTRACE_ENABLED return(cachedRegex); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! // ---------- #pragma mark Set a cached regular expression to a NSStrings UTF-16 text static NSUInteger rkl_setCachedRegexToString(RKLCachedRegex *cachedRegex, const NSRange *range, int32_t *status, id *exception RKL_UNUSED_ASSERTION_ARG) { // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv RKLCDelayedAssert((cachedRegex != NULL) && (cachedRegex->setToString != NULL) && ((range != NULL) && (NSEqualRanges(*range, NSNotFoundRange) == NO)) && (status != NULL), exception, exitNow); RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE stringUniChar = NULL; #ifdef _RKL_DTRACE_ENABLED unsigned int lookupResultFlags = 0U; #endif NSUInteger useFixedBuffer = (cachedRegex->setToLength < (CFIndex)_RKL_FIXED_LENGTH) ? 1UL : 0UL; RKLBuffer *buffer = NULL; if(cachedRegex->setToNeedsConversion == 0U) { RKLCDelayedAssert((cachedRegex->setToUniChar != NULL) && (cachedRegex->buffer == NULL), exception, exitNow); if(RKL_EXPECTED((stringUniChar = (RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE)CFStringGetCharactersPtr(cachedRegex->setToString)) == NULL, 0L)) { cachedRegex->setToUniChar = NULL; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToNeedsConversion = 1U; } else { if(RKL_EXPECTED(cachedRegex->setToUniChar != stringUniChar, 0L)) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = stringUniChar; } goto setRegexText; } } buffer = cachedRegex->buffer; RKLCDelayedAssert((buffer == NULL) ? 1 : (((buffer == &rkl_lruFixedBuffer[0]) || (buffer == &rkl_lruFixedBuffer[1]) || (buffer == &rkl_lruFixedBuffer[2]) || (buffer == &rkl_lruFixedBuffer[3])) || ((buffer == &rkl_lruDynamicBuffer[0]) || (buffer == &rkl_lruDynamicBuffer[1]) || (buffer == &rkl_lruDynamicBuffer[2]) || (buffer == &rkl_lruDynamicBuffer[3]))), exception, exitNow); if((buffer != NULL) && RKL_EXPECTED(cachedRegex->setToString == buffer->string, 1L) && RKL_EXPECTED(cachedRegex->setToHash == buffer->hash, 1L) && RKL_EXPECTED(cachedRegex->setToLength == buffer->length, 1L)) { RKLCDelayedAssert((buffer->uniChar != NULL), exception, exitNow); rkl_dtrace_addLookupFlag(lookupResultFlags, RKLCacheHitLookupFlag | RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); if(cachedRegex->setToUniChar != buffer->uniChar) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = buffer->uniChar; } goto setRegexText; } buffer = NULL; cachedRegex->buffer = NULL; NSInteger cacheWay = 0L; for(cacheWay = ((NSInteger)_RKL_LRU_CACHE_SET_WAYS - 1L); cacheWay > 0L; cacheWay--) { if(useFixedBuffer) { buffer = &rkl_lruFixedBuffer[cacheWay]; } else { buffer = &rkl_lruDynamicBuffer[cacheWay]; } if(RKL_EXPECTED(cachedRegex->setToString == buffer->string, 1L) && RKL_EXPECTED(cachedRegex->setToHash == buffer->hash, 1L) && RKL_EXPECTED(cachedRegex->setToLength == buffer->length, 1L)) { RKLCDelayedAssert((buffer->uniChar != NULL), exception, exitNow); rkl_dtrace_addLookupFlag(lookupResultFlags, RKLCacheHitLookupFlag | RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); if(cachedRegex->setToUniChar != buffer->uniChar) { cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToUniChar = buffer->uniChar; } cachedRegex->buffer = buffer; goto setRegexText; } } buffer = NULL; cachedRegex->setToUniChar = NULL; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->buffer = NULL; RKLCDelayedAssert((cachedRegex->setToNeedsConversion == 1U) && (cachedRegex->buffer == NULL), exception, exitNow); if(RKL_EXPECTED(cachedRegex->setToNeedsConversion == 1U, 1L) && RKL_EXPECTED((cachedRegex->setToUniChar = (RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE)CFStringGetCharactersPtr(cachedRegex->setToString)) != NULL, 0L)) { cachedRegex->setToNeedsConversion = 0U; cachedRegex->setToRange = NSNotFoundRange; goto setRegexText; } rkl_dtrace_addLookupFlag(lookupResultFlags, RKLConversionRequiredLookupFlag | (useFixedBuffer ? 0U : RKLDynamicBufferLookupFlag)); if(useFixedBuffer) { buffer = &rkl_lruFixedBuffer [rkl_leastRecentlyUsedWayInSet(1UL, &rkl_lruFixedBufferCacheSet, 0UL)]; } else { buffer = &rkl_lruDynamicBuffer[rkl_leastRecentlyUsedWayInSet(1UL, &rkl_lruDynamicBufferCacheSet, 0UL)]; } RKLCDelayedAssert((useFixedBuffer) ? ((buffer == &rkl_lruFixedBuffer[0]) || (buffer == &rkl_lruFixedBuffer[1]) || (buffer == &rkl_lruFixedBuffer[2]) || (buffer == &rkl_lruFixedBuffer[3])) : ((buffer == &rkl_lruDynamicBuffer[0]) || (buffer == &rkl_lruDynamicBuffer[1]) || (buffer == &rkl_lruDynamicBuffer[2]) || (buffer == &rkl_lruDynamicBuffer[3])), exception, exitNow); rkl_clearBuffer(buffer, 0UL); RKLCDelayedAssert((buffer->string == NULL) && (cachedRegex->setToString != NULL), exception, exitNow); if(RKL_EXPECTED((buffer->string = (CFStringRef)CFRetain((CFTypeRef)cachedRegex->setToString)) == NULL, 0L)) { goto exitNow; } buffer->hash = cachedRegex->setToHash; buffer->length = cachedRegex->setToLength; if(useFixedBuffer == 0UL) { RKL_STRONG_REF void * RKL_GC_VOLATILE p = (RKL_STRONG_REF void * RKL_GC_VOLATILE)buffer->uniChar; if(RKL_EXPECTED((buffer->uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&p, ((size_t)buffer->length * sizeof(UniChar)), 0UL)) == NULL, 0L)) { goto exitNow; } // Resize the buffer. } RKLCDelayedAssert((buffer->string != NULL) && (buffer->uniChar != NULL), exception, exitNow); CFStringGetCharacters(buffer->string, CFMakeRange(0L, buffer->length), (UniChar *)buffer->uniChar); // Convert to a UTF16 string. cachedRegex->setToUniChar = buffer->uniChar; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->buffer = buffer; setRegexText: if(buffer != NULL) { if(useFixedBuffer == 1UL) { rkl_accessCacheSetWay(1UL, &rkl_lruFixedBufferCacheSet, 0UL, (NSUInteger)(buffer - rkl_lruFixedBuffer)); } else { rkl_accessCacheSetWay(1UL, &rkl_lruDynamicBufferCacheSet, 0UL, (NSUInteger)(buffer - rkl_lruDynamicBuffer)); } } if(NSEqualRanges(cachedRegex->setToRange, *range) == NO) { RKLCDelayedAssert((cachedRegex->icu_regex != NULL) && (cachedRegex->setToUniChar != NULL) && (NSMaxRange(*range) <= (NSUInteger)cachedRegex->setToLength) && (cachedRegex->setToRange.length <= INT_MAX), exception, exitNow); cachedRegex->lastFindRange = cachedRegex->lastMatchRange = NSNotFoundRange; cachedRegex->setToRange = *range; RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex->icu_regex, cachedRegex->setToUniChar + cachedRegex->setToRange.location, (int32_t)cachedRegex->setToRange.length, status); rkl_dtrace_addLookupFlag(lookupResultFlags, RKLSetTextLookupFlag); if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { rkl_dtrace_addLookupFlag(lookupResultFlags, RKLErrorLookupFlag); goto exitNow; } } rkl_dtrace_utf16ConversionCache(lookupResultFlags, cachedRegex->setToString, cachedRegex->setToRange.location, cachedRegex->setToRange.length, cachedRegex->setToLength); return(1UL); // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ exitNow: #ifdef _RKL_DTRACE_ENABLED rkl_dtrace_addLookupFlag(lookupResultFlags, RKLErrorLookupFlag); if(cachedRegex != NULL) { rkl_dtrace_utf16ConversionCache(lookupResultFlags, cachedRegex->setToString, cachedRegex->setToRange.location, cachedRegex->setToRange.length, cachedRegex->setToLength); } #endif // _RKL_DTRACE_ENABLED if(cachedRegex != NULL) { cachedRegex->buffer = NULL; cachedRegex->setToRange = NSNotFoundRange; cachedRegex->lastFindRange = NSNotFoundRange; cachedRegex->lastMatchRange = NSNotFoundRange; } return(0UL); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called with rkl_cacheSpinLock already locked! // ---------- #pragma mark Get a regular expression and set it to a NSStrings UTF-16 text static RKLCachedRegex *rkl_getCachedRegexSetToString(NSString *regexString, RKLRegexOptions options, NSString *matchString, NSUInteger *matchLengthPtr, NSRange *matchRange, NSError **error, id *exception, int32_t *status) { // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv RKLCachedRegex *cachedRegex = NULL; RKLCDelayedAssert((regexString != NULL) && (matchString != NULL) && (exception != NULL) && (status != NULL) && (matchLengthPtr != NULL), exception, exitNow); if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegex(regexString, options, error, exception)) == NULL, 0L)) { goto exitNow; } RKLCDelayedAssert(((cachedRegex >= rkl_cachedRegexes) && ((cachedRegex - rkl_cachedRegexes) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->regexString != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex == rkl_lastCachedRegex), exception, exitNow); // Optimize the case where the string to search (matchString) is immutable and the setToString immutable copy is the same string with its reference count incremented. NSUInteger isSetTo = ((cachedRegex->setToString == (CFStringRef)matchString)) ? 1UL : 0UL; CFIndex matchLength = ((cachedRegex->setToIsImmutable == 1U) && (isSetTo == 1UL)) ? cachedRegex->setToLength : CFStringGetLength((CFStringRef)matchString); *matchLengthPtr = (NSUInteger)matchLength; if(matchRange->length == NSUIntegerMax) { matchRange->length = (NSUInteger)matchLength; } // For convenience, allow NSUIntegerMax == string length. if(RKL_EXPECTED((NSUInteger)matchLength < NSMaxRange(*matchRange), 0L)) { goto exitNow; } // The match range is out of bounds for the string. performRegexOp will catch and report the problem. RKLCDelayedAssert((isSetTo == 1UL) ? (cachedRegex->setToString != NULL) : 1, exception, exitNow); if(((cachedRegex->setToIsImmutable == 1U) ? isSetTo : (NSUInteger)((isSetTo == 1UL) && (cachedRegex->setToLength == matchLength) && (cachedRegex->setToHash == CFHash((CFTypeRef)matchString)))) == 0UL) { if(cachedRegex->setToString != NULL) { rkl_clearCachedRegexSetTo(cachedRegex); } cachedRegex->setToString = (CFStringRef)CFRetain((CFTypeRef)matchString); RKLCDelayedAssert(cachedRegex->setToString != NULL, exception, exitNow); cachedRegex->setToUniChar = CFStringGetCharactersPtr(cachedRegex->setToString); cachedRegex->setToNeedsConversion = (cachedRegex->setToUniChar == NULL) ? 1U : 0U; cachedRegex->setToIsImmutable = (rkl_CFStringIsMutable(cachedRegex->setToString) == YES) ? 0U : 1U; // If RKL_FAST_MUTABLE_CHECK is not defined then setToIsImmutable will always be set to '0', or in other words mutable.. cachedRegex->setToHash = CFHash((CFTypeRef)cachedRegex->setToString); cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToLength = matchLength; } if(RKL_EXPECTED(rkl_setCachedRegexToString(cachedRegex, matchRange, status, exception) == 0UL, 0L)) { cachedRegex = NULL; if(*exception == NULL) { *exception = (id)RKLCAssertDictionary(@"Failed to set up UTF16 buffer."); } goto exitNow; } exitNow: return(cachedRegex); // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // IMPORTANT! This section of code is called almost every single time that any RegexKitLite functionality is used! It /MUST/ be very fast! // ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ } #pragma mark GCC cleanup __attribute__ functions that ensure the global rkl_cacheSpinLock is properly unlocked #ifdef RKL_HAVE_CLEANUP // rkl_cleanup_cacheSpinLockStatus takes advantage of GCC's 'cleanup' variable attribute. When an 'auto' variable with the 'cleanup' attribute goes out of scope, // GCC arranges to have the designated function called. In this case, we make sure that if rkl_cacheSpinLock was locked that it was also unlocked. // If rkl_cacheSpinLock was locked, but the rkl_cacheSpinLockStatus unlocked flag was not set, we force rkl_cacheSpinLock unlocked with a call to OSSpinLockUnlock. // This is not a panacea for preventing mutex usage errors. Old style ObjC exceptions will bypass the cleanup call, but newer C++ style ObjC exceptions should cause the cleanup function to be called during the stack unwind. // We do not depend on this cleanup function being called. It is used only as an extra safety net. It is probably a bug in RegexKitLite if it is ever invoked and forced to take some kind of protective action. volatile NSUInteger rkl_debugCacheSpinLockCount = 0UL; void rkl_debugCacheSpinLock (void) RKL_ATTRIBUTES(used, noinline, visibility("default")); static void rkl_cleanup_cacheSpinLockStatus (volatile NSUInteger *rkl_cacheSpinLockStatusPtr) RKL_ATTRIBUTES(used); void rkl_debugCacheSpinLock(void) { rkl_debugCacheSpinLockCount++; // This is here primarily to prevent the optimizer from optimizing away the function. } static void rkl_cleanup_cacheSpinLockStatus(volatile NSUInteger *rkl_cacheSpinLockStatusPtr) { static NSUInteger didPrintForcedUnlockWarning = 0UL, didPrintNotLockedWarning = 0UL; NSUInteger rkl_cacheSpinLockStatus = *rkl_cacheSpinLockStatusPtr; if(RKL_EXPECTED((rkl_cacheSpinLockStatus & RKLUnlockedCacheSpinLock) == 0UL, 0L) && RKL_EXPECTED((rkl_cacheSpinLockStatus & RKLLockedCacheSpinLock) != 0UL, 1L)) { if(rkl_cacheSpinLock != (OSSpinLock)0) { if(didPrintForcedUnlockWarning == 0UL) { didPrintForcedUnlockWarning = 1UL; NSLog(@"[RegexKitLite] Unusual condition detected: Recorded that rkl_cacheSpinLock was locked, but for some reason it was not unlocked. Forcibly unlocking rkl_cacheSpinLock. Set a breakpoint at rkl_debugCacheSpinLock to debug. This warning is only printed once."); } rkl_debugCacheSpinLock(); // Since this is an unusual condition, offer an attempt to catch it before we unlock. OSSpinLockUnlock(&rkl_cacheSpinLock); } else { if(didPrintNotLockedWarning == 0UL) { didPrintNotLockedWarning = 1UL; NSLog(@"[RegexKitLite] Unusual condition detected: Recorded that rkl_cacheSpinLock was locked, but for some reason it was not unlocked, yet rkl_cacheSpinLock is currently not locked? Set a breakpoint at rkl_debugCacheSpinLock to debug. This warning is only printed once."); } rkl_debugCacheSpinLock(); } } } #endif // RKL_HAVE_CLEANUP // rkl_performDictionaryVarArgsOp is a front end to rkl_performRegexOp which converts a ', ...' varargs key/captures list and converts it in to a form that rkl_performRegexOp can use. // All error checking of arguments is handled by rkl_performRegexOp. #pragma mark Front end function that handles varargs and calls rkl_performRegexOp with the marshaled results static id rkl_performDictionaryVarArgsOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, id firstKey, va_list varArgsList) { id captureKeys[64]; int captureKeyIndexes[64]; NSUInteger captureKeysCount = 0UL; if(varArgsList != NULL) { while(captureKeysCount < 62UL) { id thisCaptureKey = (captureKeysCount == 0) ? firstKey : va_arg(varArgsList, id); if(RKL_EXPECTED(thisCaptureKey == NULL, 0L)) { break; } int thisCaptureKeyIndex = va_arg(varArgsList, int); captureKeys[captureKeysCount] = thisCaptureKey; captureKeyIndexes[captureKeysCount] = thisCaptureKeyIndex; captureKeysCount++; } } return(rkl_performRegexOp(self, _cmd, regexOp, regexString, options, capture, matchString, matchRange, replacementString, error, result, captureKeysCount, captureKeys, captureKeyIndexes)); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // ---------- #pragma mark Primary internal function that Objective-C methods call to perform regular expression operations static id rkl_performRegexOp(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, NSInteger capture, id matchString, NSRange *matchRange, NSString *replacementString, NSError **error, void *result, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount]) { volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; NSUInteger replaceMutable = 0UL; RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); BOOL dictionaryOp = ((maskedRegexOp == RKLDictionaryOfCapturesOp) || (maskedRegexOp == RKLArrayOfDictionariesOfCapturesOp)) ? YES : NO; if((error != NULL) && (*error != NULL)) { *error = NULL; } if(RKL_EXPECTED(regexString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); } if(RKL_EXPECTED(matchString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInternalInconsistencyException, @"The match string argument is NULL."); } if(RKL_EXPECTED(matchRange == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInternalInconsistencyException, @"The match range argument is NULL."); } if((maskedRegexOp == RKLReplaceOp) && RKL_EXPECTED(replacementString == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The replacement string argument is NULL."); } if((dictionaryOp == YES) && RKL_EXPECTED(captureKeys == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The keys argument is NULL."); } if((dictionaryOp == YES) && RKL_EXPECTED(captureKeyIndexes == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The captures argument is NULL."); } id resultObject = NULL, exception = NULL; int32_t status = U_ZERO_ERROR; RKLCachedRegex *cachedRegex = NULL; NSUInteger stringU16Length = 0UL, tmpIdx = 0UL; NSRange stackRanges[2048]; RKLFindAll findAll; // IMPORTANT! Once we have obtained the lock, code MUST exit via 'goto exitNow;' to unlock the lock! NO EXCEPTIONS! // ---------- OSSpinLockLock(&rkl_cacheSpinLock); // Grab the lock and get cache entry. rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; rkl_dtrace_incrementEventID(); if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegexSetToString(regexString, options, matchString, &stringU16Length, matchRange, error, &exception, &status)) == NULL, 0L)) { stringU16Length = (NSUInteger)CFStringGetLength((CFStringRef)matchString); } if(RKL_EXPECTED(matchRange->length == NSUIntegerMax, 0L)) { matchRange->length = stringU16Length; } // For convenience. if(RKL_EXPECTED(stringU16Length < NSMaxRange(*matchRange), 0L) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"Range or index out of bounds."); goto exitNow; } if(RKL_EXPECTED(stringU16Length >= (NSUInteger)INT_MAX, 0L) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"String length exceeds INT_MAX."); goto exitNow; } if(((maskedRegexOp == RKLRangeOp) || (maskedRegexOp == RKLArrayOfStringsOp)) && RKL_EXPECTED(cachedRegex != NULL, 1L) && (RKL_EXPECTED(capture < 0L, 0L) || RKL_EXPECTED(capture > cachedRegex->captureCount, 0L)) && RKL_EXPECTED(exception == NULL, 1L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture argument is not valid."); goto exitNow; } if((dictionaryOp == YES) && RKL_EXPECTED(cachedRegex != NULL, 1L) && RKL_EXPECTED(exception == NULL, 1L)) { for(tmpIdx = 0UL; tmpIdx < captureKeysCount; tmpIdx++) { if(RKL_EXPECTED(captureKeys[tmpIdx] == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture key (key %lu of %lu) is NULL.", (unsigned long)(tmpIdx + 1UL), (unsigned long)captureKeysCount); break; } if((RKL_EXPECTED(captureKeyIndexes[tmpIdx] < 0, 0L) || RKL_EXPECTED(captureKeyIndexes[tmpIdx] > cachedRegex->captureCount, 0L))) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The capture argument %d (capture %lu of %lu) for key '%@' is not valid.", captureKeyIndexes[tmpIdx], (unsigned long)(tmpIdx + 1UL), (unsigned long)captureKeysCount, captureKeys[tmpIdx]); break; } } } if(RKL_EXPECTED(cachedRegex == NULL, 0L) || RKL_EXPECTED(status > U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto exitNow; } RKLCDelayedAssert(((cachedRegex >= rkl_cachedRegexes) && ((cachedRegex - rkl_cachedRegexes) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->regexString != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex->setToString != NULL) && (cachedRegex->setToLength >= 0L) && (cachedRegex->setToUniChar != NULL) && ((CFIndex)NSMaxRange(cachedRegex->setToRange) <= cachedRegex->setToLength), &exception, exitNow); RKLCDelayedAssert((cachedRegex->setToNeedsConversion == 0U) ? ((cachedRegex->setToNeedsConversion == 0U) && (cachedRegex->setToUniChar == CFStringGetCharactersPtr(cachedRegex->setToString))) : ((cachedRegex->buffer != NULL) && (cachedRegex->setToHash == cachedRegex->buffer->hash) && (cachedRegex->setToLength == cachedRegex->buffer->length) && (cachedRegex->setToUniChar == cachedRegex->buffer->uniChar)), &exception, exitNow); switch(maskedRegexOp) { case RKLRangeOp: if((RKL_EXPECTED(rkl_search(cachedRegex, matchRange, 0UL, &exception, &status) == NO, 0L)) || (RKL_EXPECTED(status > U_ZERO_ERROR, 0L))) { *(NSRange *)result = NSNotFoundRange; goto exitNow; } if(RKL_EXPECTED(capture == 0L, 1L)) { *(NSRange *)result = cachedRegex->lastMatchRange; } else { if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, &status, (int32_t)capture, (NSRange *)result) > U_ZERO_ERROR, 0L)) { goto exitNow; } } break; case RKLSplitOp: // Fall-thru... case RKLArrayOfStringsOp: // Fall-thru... case RKLCapturesArrayOp: // Fall-thru... case RKLArrayOfCapturesOp: // Fall-thru... case RKLDictionaryOfCapturesOp: // Fall-thru... case RKLArrayOfDictionariesOfCapturesOp: findAll = rkl_makeFindAll(stackRanges, *matchRange, 2048L, (2048UL * sizeof(NSRange)), 0UL, &rkl_scratchBuffer[0], &rkl_scratchBuffer[1], &rkl_scratchBuffer[2], &rkl_scratchBuffer[3], &rkl_scratchBuffer[4], 0L, capture, (((maskedRegexOp == RKLCapturesArrayOp) || (maskedRegexOp == RKLDictionaryOfCapturesOp)) ? 1L : NSIntegerMax)); if(RKL_EXPECTED(rkl_findRanges(cachedRegex, regexOp, &findAll, &exception, &status) == NO, 1L)) { if(RKL_EXPECTED(findAll.found == 0L, 0L)) { resultObject = (maskedRegexOp == RKLDictionaryOfCapturesOp) ? [NSDictionary dictionary] : [NSArray array]; } else { if(dictionaryOp == YES) { resultObject = rkl_makeDictionary (cachedRegex, regexOp, &findAll, captureKeysCount, captureKeys, captureKeyIndexes, &exception); } else { resultObject = rkl_makeArray (cachedRegex, regexOp, &findAll, &exception); } } } for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(rkl_scratchBuffer[tmpIdx] != NULL, 0L)) { rkl_scratchBuffer[tmpIdx] = rkl_free(&rkl_scratchBuffer[tmpIdx]); } } break; case RKLReplaceOp: resultObject = rkl_replaceString(cachedRegex, matchString, stringU16Length, replacementString, (NSUInteger)CFStringGetLength((CFStringRef)replacementString), (NSInteger *)result, (replaceMutable = (((regexOp & RKLReplaceMutable) != 0) ? 1UL : 0UL)), &exception, &status); break; default: exception = RKLCAssertDictionary(@"Unknown regexOp code."); break; } exitNow: OSSpinLockUnlock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L) && RKL_EXPECTED(exception == NULL, 0L)) { exception = rkl_NSExceptionForRegex(regexString, options, NULL, status); } // If we had a problem, prepare an exception to be thrown. if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } // If there is an exception, throw it at this point. // If we're working on a mutable string and there were successful matches/replacements, then we still have work to do. // This is done outside the cache lock and with the objc replaceCharactersInRange:withString: method because Core Foundation // does not assert that the string we are attempting to update is actually a mutable string, whereas Foundation ensures // the object receiving the message is a mutable string and throws an exception if we're attempting to modify an immutable string. if(RKL_EXPECTED(replaceMutable == 1UL, 0L) && RKL_EXPECTED(*((NSInteger *)result) > 0L, 1L) && RKL_EXPECTED(status == U_ZERO_ERROR, 1L) && RKL_EXPECTED(resultObject != NULL, 1L)) { [matchString replaceCharactersInRange:*matchRange withString:resultObject]; } // If status < U_ZERO_ERROR, consider it an error, even though status < U_ZERO_ERROR is a 'warning' in ICU nomenclature. // status > U_ZERO_ERROR are an exception and handled above. // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 if(RKL_EXPECTED(status < U_ZERO_ERROR, 0L) && RKL_EXPECTED(resultObject == NULL, 0L) && (error != NULL)) { NSString *replacedString = NULL; NSInteger replacedCount = 0L; RKLUserInfoOptions userInfoOptions = RKLUserInfoNone; if((maskedRegexOp == RKLReplaceOp) && (result != NULL)) { userInfoOptions |= RKLUserInfoReplacedCount; replacedString = resultObject; replacedCount = *((NSInteger *)result); } if(matchRange != NULL) { userInfoOptions |= RKLUserInfoSubjectRange; } *error = rkl_makeNSError(userInfoOptions, regexString, options, NULL, status, matchString, (matchRange != NULL) ? *matchRange : NSNotFoundRange, replacementString, replacedString, replacedCount, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"The ICU library returned an unexpected error."); } return(resultObject); } static void rkl_handleDelayedAssert(id self, SEL _cmd, id exception) { if(RKL_EXPECTED(exception != NULL, 1L)) { if([exception isKindOfClass:[NSException class]]) { [[NSException exceptionWithName:[exception name] reason:rkl_stringFromClassAndMethod(self, _cmd, [exception reason]) userInfo:[exception userInfo]] raise]; } else { id functionString = [exception objectForKey:@"function"], fileString = [exception objectForKey:@"file"], descriptionString = [exception objectForKey:@"description"], lineNumber = [exception objectForKey:@"line"]; RKLCHardAbortAssert((functionString != NULL) && (fileString != NULL) && (descriptionString != NULL) && (lineNumber != NULL)); [[NSAssertionHandler currentHandler] handleFailureInFunction:functionString file:fileString lineNumber:(NSInteger)[lineNumber longValue] description:descriptionString]; } } } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_performRegexOp() or rkl_findRanges(). // ---------- #pragma mark Primary means of performing a search with a regular expression static NSUInteger rkl_search(RKLCachedRegex *cachedRegex, NSRange *searchRange, NSUInteger updateSearchRange, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) { NSUInteger foundMatch = 0UL; if((NSEqualRanges(*searchRange, cachedRegex->lastFindRange) == YES) && ((cachedRegex->lastMatchRange.length > 0UL) || (cachedRegex->lastMatchRange.location == (NSUInteger)NSNotFound))) { foundMatch = ((cachedRegex->lastMatchRange.location == (NSUInteger)NSNotFound) ? 0UL : 1UL);} else { // Only perform an expensive 'find' operation iff the current find range is different than the last find range. NSUInteger findLocation = (searchRange->location - cachedRegex->setToRange.location); RKLCDelayedAssert(((searchRange->location >= cachedRegex->setToRange.location)) && (NSRangeInsideRange(*searchRange, cachedRegex->setToRange) == YES) && (findLocation < INT_MAX) && (findLocation <= cachedRegex->setToRange.length), exception, exitNow); RKL_PREFETCH_UNICHAR(cachedRegex->setToUniChar, searchRange->location); // Spool up the CPU caches. // Using uregex_findNext can be a slight performance win. NSUInteger useFindNext = (RKL_EXPECTED(searchRange->location == (NSMaxRange(cachedRegex->lastMatchRange) + ((RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.location < NSMaxRange(cachedRegex->setToRange), 0L)) ? 1UL : 0UL)), 1L) ? 1UL : 0UL); cachedRegex->lastFindRange = *searchRange; if(RKL_EXPECTED(useFindNext == 0UL, 0L)) { if(RKL_EXPECTED((RKL_ICU_FUNCTION_APPEND(uregex_find) (cachedRegex->icu_regex, (int32_t)findLocation, status) == NO), 0L) || RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto finishedFind; } } else { if(RKL_EXPECTED((RKL_ICU_FUNCTION_APPEND(uregex_findNext)(cachedRegex->icu_regex, status) == NO), 0L) || RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto finishedFind; } } foundMatch = 1UL; if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, 0, &cachedRegex->lastMatchRange) > U_ZERO_ERROR, 0L)) { goto finishedFind; } RKLCDelayedAssert(NSRangeInsideRange(cachedRegex->lastMatchRange, *searchRange) == YES, exception, exitNow); } finishedFind: if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { foundMatch = 0UL; cachedRegex->lastFindRange = NSNotFoundRange; } if(RKL_EXPECTED(foundMatch == 0UL, 0L)) { cachedRegex->lastFindRange = NSNotFoundRange; cachedRegex->lastMatchRange = NSNotFoundRange; if(RKL_EXPECTED(updateSearchRange == 1UL, 1L)) { *searchRange = NSMakeRange(NSMaxRange(*searchRange), 0UL); } } else { RKLCDelayedAssert(NSRangeInsideRange(cachedRegex->lastMatchRange, *searchRange) == YES, exception, exitNow); if(RKL_EXPECTED(updateSearchRange == 1UL, 1L)) { NSUInteger nextLocation = (NSMaxRange(cachedRegex->lastMatchRange) + ((RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.location < NSMaxRange(cachedRegex->setToRange), 1L)) ? 1UL : 0UL)), locationDiff = nextLocation - searchRange->location; RKLCDelayedAssert((((locationDiff > 0UL) || ((locationDiff == 0UL) && (cachedRegex->lastMatchRange.location == NSMaxRange(cachedRegex->setToRange)))) && (locationDiff <= searchRange->length)), exception, exitNow); searchRange->location = nextLocation; searchRange->length -= locationDiff; } } #ifndef NS_BLOCK_ASSERTIONS exitNow: #endif return(foundMatch); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_performRegexOp() or rkl_performEnumerationUsingBlock(). // ---------- #pragma mark Used to perform multiple searches at once and return the NSRange results in bulk static BOOL rkl_findRanges(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception, int32_t *status) { BOOL returnWithError = YES; RKLCDelayedAssert((((cachedRegex != NULL) && (cachedRegex->icu_regex != NULL) && (cachedRegex->setToUniChar != NULL) && (cachedRegex->captureCount >= 0L) && (cachedRegex->setToRange.location != (NSUInteger)NSNotFound)) && (status != NULL) && ((findAll != NULL) && (findAll->found == 0L) && (findAll->addedSplitRanges == 0L) && ((findAll->capacity >= 0L) && (((findAll->capacity > 0L) || (findAll->size > 0UL)) ? ((findAll->ranges != NULL) && (findAll->capacity > 0L) && (findAll->size > 0UL)) : 1)) && ((findAll->capture >= 0L) && (findAll->capture <= cachedRegex->captureCount)))), exception, exitNow); NSInteger captureCount = cachedRegex->captureCount, findAllRangeIndexOfLastNonZeroLength = 0L; NSUInteger lastLocation = findAll->findInRange.location; RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); NSRange searchRange = findAll->findInRange; for(findAll->found = 0L; (findAll->found < findAll->findUpTo) && ((findAll->found < findAll->capacity) || (findAll->found == 0L)); findAll->found++) { NSInteger loopCapture, shouldBreak = 0L; if(RKL_EXPECTED(findAll->found >= ((findAll->capacity - ((captureCount + 2L) * 4L)) - 4L), 0L)) { if(RKL_EXPECTED(rkl_growFindRanges(cachedRegex, lastLocation, findAll, exception) == 0UL, 0L)) { goto exitNow; } } RKLCDelayedAssert((searchRange.location != (NSUInteger)NSNotFound) && (NSRangeInsideRange(searchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(findAll->findInRange, cachedRegex->setToRange) == YES), exception, exitNow); // This fixes a 'bug' that is also present in ICU's uregex_split(). 'Bug', in this case, means that the results of a split operation can differ from those that perl's split() creates for the same input. // "I|at|ice I eat rice" split using the regex "\b\s*" demonstrates the problem. ICU bug http://bugs.icu-project.org/trac/ticket/6826 // ICU : "", "I", "|", "at", "|", "ice", "", "I", "", "eat", "", "rice" <- Results that RegexKitLite used to produce. // PERL: "I", "|", "at", "|", "ice", "I", "eat", "rice" <- Results that RegexKitLite now produces. do { if((rkl_search(cachedRegex, &searchRange, 1UL, exception, status) == NO) || (RKL_EXPECTED(*status > U_ZERO_ERROR, 0L))) { shouldBreak = 1L; } findAll->remainingRange = searchRange; } while(RKL_EXPECTED((cachedRegex->lastMatchRange.location - lastLocation) == 0UL, 0L) && RKL_EXPECTED(cachedRegex->lastMatchRange.length == 0UL, 0L) && (maskedRegexOp == RKLSplitOp) && RKL_EXPECTED(shouldBreak == 0L, 1L)); if(RKL_EXPECTED(shouldBreak == 1L, 0L)) { break; } RKLCDelayedAssert((searchRange.location != (NSUInteger)NSNotFound) && (NSRangeInsideRange(searchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(findAll->findInRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(searchRange, findAll->findInRange) == YES), exception, exitNow); RKLCDelayedAssert((NSRangeInsideRange(cachedRegex->lastFindRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(cachedRegex->lastMatchRange, cachedRegex->setToRange) == YES) && (NSRangeInsideRange(cachedRegex->lastMatchRange, findAll->findInRange) == YES), exception, exitNow); RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->capacity >= 0L) && ((findAll->found + (captureCount + 3L) + 1L) < (findAll->capacity - 2L)), exception, exitNow); NSInteger findAllRangesIndexForCapture0 = findAll->found; switch(maskedRegexOp) { case RKLArrayOfStringsOp: if(findAll->capture == 0L) { findAll->ranges[findAll->found] = cachedRegex->lastMatchRange; } else { if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, (int32_t)findAll->capture, &findAll->ranges[findAll->found]) > U_ZERO_ERROR, 0L)) { goto exitNow; } } break; case RKLSplitOp: // Fall-thru... case RKLCapturesArrayOp: // Fall-thru... case RKLDictionaryOfCapturesOp: // Fall-thru... case RKLArrayOfDictionariesOfCapturesOp: // Fall-thru... case RKLArrayOfCapturesOp: findAll->ranges[findAll->found] = ((maskedRegexOp == RKLSplitOp) ? NSMakeRange(lastLocation, cachedRegex->lastMatchRange.location - lastLocation) : cachedRegex->lastMatchRange); for(loopCapture = 1L; loopCapture <= captureCount; loopCapture++) { RKLCDelayedAssert((findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)) && (loopCapture < INT_MAX), exception, exitNow); if(RKL_EXPECTED(rkl_getRangeForCapture(cachedRegex, status, (int32_t)loopCapture, &findAll->ranges[++findAll->found]) > U_ZERO_ERROR, 0L)) { goto exitNow; } } break; default: if(*exception == NULL) { *exception = RKLCAssertDictionary(@"Unknown regexOp."); } goto exitNow; break; } if(findAll->ranges[findAllRangesIndexForCapture0].length > 0UL) { findAllRangeIndexOfLastNonZeroLength = findAll->found + 1UL; } lastLocation = NSMaxRange(cachedRegex->lastMatchRange); } if(RKL_EXPECTED(*status > U_ZERO_ERROR, 0L)) { goto exitNow; } RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)), exception, exitNow); if(maskedRegexOp == RKLSplitOp) { if(lastLocation != NSMaxRange(findAll->findInRange)) { findAll->addedSplitRanges++; findAll->ranges[findAll->found++] = NSMakeRange(lastLocation, NSMaxRange(findAll->findInRange) - lastLocation); findAllRangeIndexOfLastNonZeroLength = findAll->found; } findAll->found = findAllRangeIndexOfLastNonZeroLength; } RKLCDelayedAssert((findAll->ranges != NULL) && (findAll->found >= 0L) && (findAll->found < (findAll->capacity - 2L)), exception, exitNow); returnWithError = NO; exitNow: return(returnWithError); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_findRanges(). // ---------- static NSUInteger rkl_growFindRanges(RKLCachedRegex *cachedRegex, NSUInteger lastLocation, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) { NSUInteger didGrowRanges = 0UL; RKLCDelayedAssert((((cachedRegex != NULL) && (cachedRegex->captureCount >= 0L)) && ((findAll != NULL) && (findAll->capacity >= 0L) && (findAll->rangesScratchBuffer != NULL) && (findAll->found >= 0L) && (((findAll->capacity > 0L) || (findAll->size > 0UL) || (findAll->ranges != NULL)) ? ((findAll->capacity > 0L) && (findAll->size > 0UL) && (findAll->ranges != NULL) && (((size_t)findAll->capacity * sizeof(NSRange)) == findAll->size)) : 1))), exception, exitNow); // Attempt to guesstimate the required capacity based on: the total length needed to search / (length we've searched so far / ranges found so far). NSInteger newCapacity = (findAll->capacity + (findAll->capacity / 2L)), estimate = (NSInteger)((float)cachedRegex->setToLength / (((float)lastLocation + 1.0f) / ((float)findAll->found + 1.0f))); newCapacity = (((newCapacity + ((estimate > newCapacity) ? estimate : newCapacity)) / 2L) + ((cachedRegex->captureCount + 2L) * 4L) + 4L); NSUInteger needToCopy = ((*findAll->rangesScratchBuffer != findAll->ranges) && (findAll->ranges != NULL)) ? 1UL : 0UL; // If findAll->ranges is set to a stack allocation then we need to manually copy the data from the stack to the new heap allocation. size_t newSize = ((size_t)newCapacity * sizeof(NSRange)); RKL_STRONG_REF NSRange * RKL_GC_VOLATILE newRanges = NULL; if(RKL_EXPECTED((newRanges = (RKL_STRONG_REF NSRange * RKL_GC_VOLATILE)rkl_realloc((RKL_STRONG_REF void ** RKL_GC_VOLATILE)findAll->rangesScratchBuffer, newSize, 0UL)) == NULL, 0L)) { findAll->capacity = 0L; findAll->size = 0UL; findAll->ranges = NULL; *findAll->rangesScratchBuffer = rkl_free((RKL_STRONG_REF void ** RKL_GC_VOLATILE)findAll->rangesScratchBuffer); goto exitNow; } else { didGrowRanges = 1UL; } if(needToCopy == 1UL) { memcpy(newRanges, findAll->ranges, findAll->size); } // If necessary, copy the existing data to the new heap allocation. findAll->capacity = newCapacity; findAll->size = newSize; findAll->ranges = newRanges; exitNow: return(didGrowRanges); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_performRegexOp(). // ---------- #pragma mark Convert bulk results from rkl_findRanges in to various NSArray types static NSArray *rkl_makeArray(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, id *exception RKL_UNUSED_ASSERTION_ARG) { NSUInteger createdStringsCount = 0UL, createdArraysCount = 0UL, transferredStringsCount = 0UL; id * RKL_GC_VOLATILE matchedStrings = NULL, * RKL_GC_VOLATILE subcaptureArrays = NULL, emptyString = @""; NSArray * RKL_GC_VOLATILE resultArray = NULL; RKLCDelayedAssert((cachedRegex != NULL) && ((findAll != NULL) && (findAll->found >= 0L) && (findAll->stringsScratchBuffer != NULL) && (findAll->arraysScratchBuffer != NULL)), exception, exitNow); size_t matchedStringsSize = ((size_t)findAll->found * sizeof(id)); CFStringRef setToString = cachedRegex->setToString; if((findAll->stackUsed + matchedStringsSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)alloca(matchedStringsSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedStringsSize; } else { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->stringsScratchBuffer, matchedStringsSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } { // This sub-block (and its local variables) is here for the benefit of the optimizer. NSUInteger found = (NSUInteger)findAll->found; const NSRange *rangePtr = findAll->ranges; id *matchedStringsPtr = matchedStrings; for(createdStringsCount = 0UL; createdStringsCount < found; createdStringsCount++) { NSRange range = *rangePtr++; if(RKL_EXPECTED(((*matchedStringsPtr++ = RKL_EXPECTED(range.length == 0UL, 0L) ? emptyString : rkl_CreateStringWithSubstring((id)setToString, range)) == NULL), 0L)) { goto exitNow; } } } NSUInteger arrayCount = createdStringsCount; id * RKL_GC_VOLATILE arrayObjects = matchedStrings; if((regexOp & RKLSubcapturesArray) != 0UL) { RKLCDelayedAssert(((createdStringsCount % ((NSUInteger)cachedRegex->captureCount + 1UL)) == 0UL) && (createdArraysCount == 0UL), exception, exitNow); NSUInteger captureCount = ((NSUInteger)cachedRegex->captureCount + 1UL); NSUInteger subcaptureArraysCount = (createdStringsCount / captureCount); size_t subcaptureArraysSize = ((size_t)subcaptureArraysCount * sizeof(id)); if((findAll->stackUsed + subcaptureArraysSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((subcaptureArrays = (id * RKL_GC_VOLATILE)alloca(subcaptureArraysSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += subcaptureArraysSize; } else { if(RKL_EXPECTED((subcaptureArrays = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->arraysScratchBuffer, subcaptureArraysSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } { // This sub-block (and its local variables) is here for the benefit of the optimizer. id *subcaptureArraysPtr = subcaptureArrays; id *matchedStringsPtr = matchedStrings; for(createdArraysCount = 0UL; createdArraysCount < subcaptureArraysCount; createdArraysCount++) { if(RKL_EXPECTED((*subcaptureArraysPtr++ = rkl_CreateArrayWithObjects((void **)matchedStringsPtr, captureCount)) == NULL, 0L)) { goto exitNow; } matchedStringsPtr += captureCount; transferredStringsCount += captureCount; } } RKLCDelayedAssert((transferredStringsCount == createdStringsCount), exception, exitNow); arrayCount = createdArraysCount; arrayObjects = subcaptureArrays; } RKLCDelayedAssert((arrayObjects != NULL), exception, exitNow); resultArray = rkl_CreateAutoreleasedArray((void **)arrayObjects, (NSUInteger)arrayCount); exitNow: if(RKL_EXPECTED(resultArray == NULL, 0L) && (rkl_collectingEnabled() == NO)) { // If we did not create an array then we need to make sure that we release any objects we created. NSUInteger x; if(matchedStrings != NULL) { for(x = transferredStringsCount; x < createdStringsCount; x++) { if((matchedStrings[x] != NULL) && (matchedStrings[x] != emptyString)) { matchedStrings[x] = rkl_ReleaseObject(matchedStrings[x]); } } } if(subcaptureArrays != NULL) { for(x = 0UL; x < createdArraysCount; x++) { if(subcaptureArrays[x] != NULL) { subcaptureArrays[x] = rkl_ReleaseObject(subcaptureArrays[x]); } } } } return(resultArray); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_performRegexOp(). // ---------- #pragma mark Convert bulk results from rkl_findRanges in to various NSDictionary types static id rkl_makeDictionary(RKLCachedRegex *cachedRegex, RKLRegexOp regexOp, RKLFindAll *findAll, NSUInteger captureKeysCount, id captureKeys[captureKeysCount], const int captureKeyIndexes[captureKeysCount], id *exception RKL_UNUSED_ASSERTION_ARG) { NSUInteger matchedStringIndex = 0UL, createdStringsCount = 0UL, createdDictionariesCount = 0UL, matchedDictionariesCount = (findAll->found / (cachedRegex->captureCount + 1UL)), transferredDictionariesCount = 0UL; id * RKL_GC_VOLATILE matchedStrings = NULL, * RKL_GC_VOLATILE matchedKeys = NULL, emptyString = @""; id RKL_GC_VOLATILE returnObject = NULL; NSDictionary ** RKL_GC_VOLATILE matchedDictionaries = NULL; RKLCDelayedAssert((cachedRegex != NULL) && ((findAll != NULL) && (findAll->found >= 0L) && (findAll->stringsScratchBuffer != NULL) && (findAll->dictionariesScratchBuffer != NULL) && (findAll->keysScratchBuffer != NULL) && (captureKeyIndexes != NULL)), exception, exitNow); CFStringRef setToString = cachedRegex->setToString; size_t matchedStringsSize = ((size_t)captureKeysCount * sizeof(void *)); if((findAll->stackUsed + matchedStringsSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)alloca(matchedStringsSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedStringsSize; } else { if(RKL_EXPECTED((matchedStrings = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->stringsScratchBuffer, matchedStringsSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } size_t matchedKeysSize = ((size_t)captureKeysCount * sizeof(void *)); if((findAll->stackUsed + matchedKeysSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedKeys = (id * RKL_GC_VOLATILE)alloca(matchedKeysSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedKeysSize; } else { if(RKL_EXPECTED((matchedKeys = (id * RKL_GC_VOLATILE)rkl_realloc(findAll->keysScratchBuffer, matchedKeysSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } size_t matchedDictionariesSize = ((size_t)matchedDictionariesCount * sizeof(NSDictionary *)); if((findAll->stackUsed + matchedDictionariesSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((matchedDictionaries = (NSDictionary ** RKL_GC_VOLATILE)alloca(matchedDictionariesSize)) == NULL, 0L)) { goto exitNow; } findAll->stackUsed += matchedDictionariesSize; } else { if(RKL_EXPECTED((matchedDictionaries = (NSDictionary ** RKL_GC_VOLATILE)rkl_realloc(findAll->dictionariesScratchBuffer, matchedDictionariesSize, (NSUInteger)RKLScannedOption)) == NULL, 0L)) { goto exitNow; } } { // This sub-block (and its local variables) is here for the benefit of the optimizer. NSUInteger captureCount = cachedRegex->captureCount; NSDictionary **matchedDictionariesPtr = matchedDictionaries; for(createdDictionariesCount = 0UL; createdDictionariesCount < matchedDictionariesCount; createdDictionariesCount++) { RKLCDelayedAssert(((createdDictionariesCount * captureCount) < (NSUInteger)findAll->found), exception, exitNow); RKL_STRONG_REF const NSRange * RKL_GC_VOLATILE rangePtr = &findAll->ranges[(createdDictionariesCount * (captureCount + 1UL))]; for(matchedStringIndex = 0UL; matchedStringIndex < captureKeysCount; matchedStringIndex++) { NSRange range = rangePtr[captureKeyIndexes[matchedStringIndex]]; if(RKL_EXPECTED(range.location != NSNotFound, 0L)) { if(RKL_EXPECTED(((matchedStrings[createdStringsCount] = RKL_EXPECTED(range.length == 0UL, 0L) ? emptyString : rkl_CreateStringWithSubstring((id)setToString, range)) == NULL), 0L)) { goto exitNow; } matchedKeys[createdStringsCount] = captureKeys[createdStringsCount]; createdStringsCount++; } } RKLCDelayedAssert((matchedStringIndex <= captureCount), exception, exitNow); if(RKL_EXPECTED(((*matchedDictionariesPtr++ = (NSDictionary * RKL_GC_VOLATILE)CFDictionaryCreate(NULL, (const void **)matchedKeys, (const void **)matchedStrings, (CFIndex)createdStringsCount, &rkl_transferOwnershipDictionaryKeyCallBacks, &rkl_transferOwnershipDictionaryValueCallBacks)) == NULL), 0L)) { goto exitNow; } createdStringsCount = 0UL; } } if(createdDictionariesCount > 0UL) { if((regexOp & RKLMaskOp) == RKLArrayOfDictionariesOfCapturesOp) { RKLCDelayedAssert((matchedDictionaries != NULL) && (createdDictionariesCount > 0UL), exception, exitNow); if((returnObject = rkl_CreateAutoreleasedArray((void **)matchedDictionaries, createdDictionariesCount)) == NULL) { goto exitNow; } transferredDictionariesCount = createdDictionariesCount; } else { RKLCDelayedAssert((matchedDictionaries != NULL) && (createdDictionariesCount == 1UL), exception, exitNow); if((returnObject = rkl_CFAutorelease(matchedDictionaries[0])) == NULL) { goto exitNow; } transferredDictionariesCount = 1UL; } } exitNow: RKLCDelayedAssert((createdDictionariesCount <= transferredDictionariesCount) && ((transferredDictionariesCount > 0UL) ? (createdStringsCount == 0UL) : 1), exception, exitNow2); #ifndef NS_BLOCK_ASSERTIONS exitNow2: #endif if(rkl_collectingEnabled() == NO) { // Release any objects, if necessary. NSUInteger x; if(matchedStrings != NULL) { for(x = 0UL; x < createdStringsCount; x++) { if((matchedStrings[x] != NULL) && (matchedStrings[x] != emptyString)) { matchedStrings[x] = rkl_ReleaseObject(matchedStrings[x]); } } } if(matchedDictionaries != NULL) { for(x = transferredDictionariesCount; x < createdDictionariesCount; x++) { if((matchedDictionaries[x] != NULL)) { matchedDictionaries[x] = rkl_ReleaseObject(matchedDictionaries[x]); } } } } return(returnObject); } // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // IMPORTANT! Should only be called from rkl_performRegexOp(). // ---------- #pragma mark Perform "search and replace" operations on strings using ICUs uregex_*replace* functions static NSString *rkl_replaceString(RKLCachedRegex *cachedRegex, id searchString, NSUInteger searchU16Length, NSString *replacementString, NSUInteger replacementU16Length, NSInteger *replacedCountPtr, NSUInteger replaceMutable, id *exception, int32_t *status) { RKL_STRONG_REF UniChar * RKL_GC_VOLATILE tempUniCharBuffer = NULL; RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar = NULL; uint64_t searchU16Length64 = (uint64_t)searchU16Length, replacementU16Length64 = (uint64_t)replacementU16Length; int32_t resultU16Length = 0, tempUniCharBufferU16Capacity = 0, needU16Capacity = 0; id RKL_GC_VOLATILE resultObject = NULL; NSInteger replacedCount = -1L; if((RKL_EXPECTED(replacementU16Length64 >= (uint64_t)INT_MAX, 0L) || RKL_EXPECTED(((searchU16Length64 / 2ULL) + (replacementU16Length64 * 2ULL)) >= (uint64_t)INT_MAX, 0L))) { *exception = [NSException exceptionWithName:NSRangeException reason:@"Replacement string length exceeds INT_MAX." userInfo:NULL]; goto exitNow; } RKLCDelayedAssert((searchU16Length64 < (uint64_t)INT_MAX) && (replacementU16Length64 < (uint64_t)INT_MAX) && (((searchU16Length64 / 2ULL) + (replacementU16Length64 * 2ULL)) < (uint64_t)INT_MAX), exception, exitNow); // Zero order approximation of the buffer sizes for holding the replaced string or split strings and split strings pointer offsets. As UTF16 code units. tempUniCharBufferU16Capacity = (int32_t)(16UL + (searchU16Length + (searchU16Length / 2UL)) + (replacementU16Length * 2UL)); RKLCDelayedAssert((tempUniCharBufferU16Capacity < INT_MAX) && (tempUniCharBufferU16Capacity > 0), exception, exitNow); // Buffer sizes converted from native units to bytes. size_t stackSize = 0UL, replacementSize = ((size_t)replacementU16Length * sizeof(UniChar)), tempUniCharBufferSize = ((size_t)tempUniCharBufferU16Capacity * sizeof(UniChar)); // For the various buffers we require, we first try to allocate from the stack if we're not over the RKL_STACK_LIMIT. If we are, switch to using the heap for the buffer. if((stackSize + tempUniCharBufferSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(tempUniCharBufferSize)) == NULL, 0L)) { goto exitNow; } stackSize += tempUniCharBufferSize; } else { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], tempUniCharBufferSize, 0UL)) == NULL, 0L)) { goto exitNow; } } // Try to get the pointer to the replacement strings UTF16 data. If we can't, allocate some buffer space, then covert to UTF16. if((replacementUniChar = CFStringGetCharactersPtr((CFStringRef)replacementString)) == NULL) { RKL_STRONG_REF UniChar * RKL_GC_VOLATILE uniCharBuffer = NULL; if((stackSize + replacementSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(replacementSize)) == NULL, 0L)) { goto exitNow; } stackSize += replacementSize; } else { if(RKL_EXPECTED((uniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[1], replacementSize, 0UL)) == NULL, 0L)) { goto exitNow; } } CFStringGetCharacters((CFStringRef)replacementString, CFMakeRange(0L, replacementU16Length), uniCharBuffer); // Convert to a UTF16 string. replacementUniChar = uniCharBuffer; } resultU16Length = rkl_replaceAll(cachedRegex, replacementUniChar, (int32_t)replacementU16Length, tempUniCharBuffer, tempUniCharBufferU16Capacity, &replacedCount, &needU16Capacity, exception, status); RKLCDelayedAssert((resultU16Length <= tempUniCharBufferU16Capacity) && (needU16Capacity >= resultU16Length) && (needU16Capacity >= 0), exception, exitNow); if(RKL_EXPECTED((needU16Capacity + 4) >= INT_MAX, 0L)) { *exception = [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Replaced string length exceeds INT_MAX." userInfo:NULL]; goto exitNow; } if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { // Our buffer guess(es) were too small. Resize the buffers and try again. // rkl_replaceAll will turn a status of U_STRING_NOT_TERMINATED_WARNING in to a U_BUFFER_OVERFLOW_ERROR. // As an extra precaution, we pad out the amount needed by an extra four characters "just in case". // http://lists.apple.com/archives/Cocoa-dev/2010/Jan/msg01011.html needU16Capacity += 4; tempUniCharBufferSize = ((size_t)(tempUniCharBufferU16Capacity = needU16Capacity + 4) * sizeof(UniChar)); // Use needU16Capacity. Bug 2890810. if((stackSize + tempUniCharBufferSize) < (size_t)_RKL_STACK_LIMIT) { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)alloca(tempUniCharBufferSize)) == NULL, 0L)) { goto exitNow; } stackSize += tempUniCharBufferSize; } // Warning about stackSize can be safely ignored. else { if(RKL_EXPECTED((tempUniCharBuffer = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc(&rkl_scratchBuffer[0], tempUniCharBufferSize, 0UL)) == NULL, 0L)) { goto exitNow; } } *status = U_ZERO_ERROR; // Make sure the status var is cleared and try again. resultU16Length = rkl_replaceAll(cachedRegex, replacementUniChar, (int32_t)replacementU16Length, tempUniCharBuffer, tempUniCharBufferU16Capacity, &replacedCount, &needU16Capacity, exception, status); RKLCDelayedAssert((resultU16Length <= tempUniCharBufferU16Capacity) && (needU16Capacity >= resultU16Length) && (needU16Capacity >= 0), exception, exitNow); } // If status != U_ZERO_ERROR, consider it an error, even though status < U_ZERO_ERROR is a 'warning' in ICU nomenclature. // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 if(RKL_EXPECTED(*status != U_ZERO_ERROR, 0L)) { goto exitNow; } // Something went wrong. RKLCDelayedAssert((replacedCount >= 0L), exception, exitNow); if(RKL_EXPECTED(resultU16Length == 0, 0L)) { resultObject = @""; } // Optimize the case where the replaced text length == 0 with a @"" string. else if(RKL_EXPECTED((NSUInteger)resultU16Length == searchU16Length, 0L) && RKL_EXPECTED(replacedCount == 0L, 1L)) { // Optimize the case where the replacement == original by creating a copy. Very fast if self is immutable. if(replaceMutable == 0UL) { resultObject = rkl_CFAutorelease(CFStringCreateCopy(NULL, (CFStringRef)searchString)); } // .. but only if this is not replacing a mutable self. Warning about potential leak can be safely ignored. } else { resultObject = rkl_CFAutorelease(CFStringCreateWithCharacters(NULL, tempUniCharBuffer, (CFIndex)resultU16Length)); } // otherwise, create a new string. Warning about potential leak can be safely ignored. // If replaceMutable == 1UL, we don't do the replacement here. We wait until after we return and unlock the cache lock. // This is because we may be trying to mutate an immutable string object. if((replaceMutable == 1UL) && RKL_EXPECTED(replacedCount > 0L, 1L)) { // We're working on a mutable string and there were successful matches with replaced text, so there's work to do. if(cachedRegex->buffer != NULL) { rkl_clearBuffer(cachedRegex->buffer, 0UL); cachedRegex->buffer = NULL; } NSUInteger idx = 0UL; for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { RKLBuffer *buffer = ((NSUInteger)cachedRegex->setToLength < _RKL_FIXED_LENGTH) ? &rkl_lruFixedBuffer[idx] : &rkl_lruDynamicBuffer[idx]; if(RKL_EXPECTED(cachedRegex->setToString == buffer->string, 0L) && (cachedRegex->setToLength == buffer->length) && (cachedRegex->setToHash == buffer->hash)) { rkl_clearBuffer(buffer, 0UL); } } rkl_clearCachedRegexSetTo(cachedRegex); // Flush any cached information about this string since it will mutate. } exitNow: if(RKL_EXPECTED(status == NULL, 0L) || RKL_EXPECTED(*status != U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception == NULL, 0L) || RKL_EXPECTED(*exception != NULL, 0L)) { replacedCount = -1L; } if(rkl_scratchBuffer[0] != NULL) { rkl_scratchBuffer[0] = rkl_free(&rkl_scratchBuffer[0]); } if(rkl_scratchBuffer[1] != NULL) { rkl_scratchBuffer[1] = rkl_free(&rkl_scratchBuffer[1]); } if(replacedCountPtr != NULL) { *replacedCountPtr = replacedCount; } return(resultObject); } // The two warnings about potential leaks can be safely ignored. // IMPORTANT! Should only be called from rkl_replaceString(). // ---------- // Modified version of the ICU libraries uregex_replaceAll() that keeps count of the number of replacements made. static int32_t rkl_replaceAll(RKLCachedRegex *cachedRegex, RKL_STRONG_REF const UniChar * RKL_GC_VOLATILE replacementUniChar, int32_t replacementU16Length, UniChar *replacedUniChar, int32_t replacedU16Capacity, NSInteger *replacedCount, int32_t *needU16Capacity, id *exception RKL_UNUSED_ASSERTION_ARG, int32_t *status) { int32_t u16Length = 0, initialReplacedU16Capacity = replacedU16Capacity; NSUInteger bufferOverflowed = 0UL; NSInteger replaced = -1L; RKLCDelayedAssert((cachedRegex != NULL) && (replacementUniChar != NULL) && (replacedUniChar != NULL) && (replacedCount != NULL) && (needU16Capacity != NULL) && (status != NULL) && (replacementU16Length >= 0) && (replacedU16Capacity >= 0), exception, exitNow); cachedRegex->lastFindRange = cachedRegex->lastMatchRange = NSNotFoundRange; // Clear the cached find information for this regex so a subsequent find works correctly. RKL_ICU_FUNCTION_APPEND(uregex_reset)(cachedRegex->icu_regex, 0, status); // Work around for ICU uregex_reset() bug, see http://bugs.icu-project.org/trac/ticket/6545 // http://sourceforge.net/tracker/index.php?func=detail&aid=2105213&group_id=204582&atid=990188 if(RKL_EXPECTED(cachedRegex->setToRange.length == 0UL, 0L) && (*status == U_INDEX_OUTOFBOUNDS_ERROR)) { *status = U_ZERO_ERROR; } replaced = 0L; // This loop originally came from ICU source/i18n/uregex.cpp, uregex_replaceAll. // There is a bug in that code which causes the size of the buffer required for the replaced text to not be calculated correctly. // This contains a work around using the variable bufferOverflowed. // ICU bug: http://bugs.icu-project.org/trac/ticket/6656 // http://sourceforge.net/tracker/index.php?func=detail&aid=2408447&group_id=204582&atid=990188 while(RKL_ICU_FUNCTION_APPEND(uregex_findNext)(cachedRegex->icu_regex, status)) { replaced++; u16Length += RKL_ICU_FUNCTION_APPEND(uregex_appendReplacement)(cachedRegex->icu_regex, replacementUniChar, replacementU16Length, &replacedUniChar, &replacedU16Capacity, status); if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { bufferOverflowed = 1UL; *status = U_ZERO_ERROR; } } if(RKL_EXPECTED(*status == U_BUFFER_OVERFLOW_ERROR, 0L)) { bufferOverflowed = 1UL; *status = U_ZERO_ERROR; } if(RKL_EXPECTED(*status <= U_ZERO_ERROR, 1L)) { u16Length += RKL_ICU_FUNCTION_APPEND(uregex_appendTail)(cachedRegex->icu_regex, &replacedUniChar, &replacedU16Capacity, status); } // Try to work around a status of U_STRING_NOT_TERMINATED_WARNING. For now, we treat it as a "Buffer Overflow" error. // As an extra precaution, in rkl_replaceString, we pad out the amount needed by an extra four characters "just in case". // http://lists.apple.com/archives/Cocoa-dev/2010/Jan/msg01011.html if(RKL_EXPECTED(*status == U_STRING_NOT_TERMINATED_WARNING, 0L)) { *status = U_BUFFER_OVERFLOW_ERROR; } // Check for status <= U_ZERO_ERROR (a 'warning' in ICU nomenclature) rather than just status == U_ZERO_ERROR. // Under just the right circumstances, status might be equal to U_STRING_NOT_TERMINATED_WARNING. When this occurred, // rkl_replaceString would never get the U_BUFFER_OVERFLOW_ERROR status, and thus never grow the buffer to the size needed. // http://sourceforge.net/tracker/?func=detail&atid=990188&aid=2890810&group_id=204582 if(RKL_EXPECTED(bufferOverflowed == 1UL, 0L) && RKL_EXPECTED(*status <= U_ZERO_ERROR, 1L)) { *status = U_BUFFER_OVERFLOW_ERROR; } #ifndef NS_BLOCK_ASSERTIONS exitNow: #endif // NS_BLOCK_ASSERTIONS if(RKL_EXPECTED(replacedCount != NULL, 1L)) { *replacedCount = replaced; } if(RKL_EXPECTED(needU16Capacity != NULL, 1L)) { *needU16Capacity = u16Length; } // Use needU16Capacity to return the number of characters that are needed for the completely replaced string. Bug 2890810. return(initialReplacedU16Capacity - replacedU16Capacity); // Return the number of characters of replacedUniChar that were used. } #pragma mark Internal function used to check if a regular expression is valid. static NSUInteger rkl_isRegexValid(id self, SEL _cmd, NSString *regex, RKLRegexOptions options, NSInteger *captureCountPtr, NSError **error) { volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; RKLCachedRegex *cachedRegex = NULL; NSUInteger gotCachedRegex = 0UL; NSInteger captureCount = -1L; id exception = NULL; if((error != NULL) && (*error != NULL)) { *error = NULL; } if(RKL_EXPECTED(regex == NULL, 0L)) { RKL_RAISE_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); } OSSpinLockLock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; rkl_dtrace_incrementEventID(); if(RKL_EXPECTED((cachedRegex = rkl_getCachedRegex(regex, options, error, &exception)) != NULL, 1L)) { gotCachedRegex = 1UL; captureCount = cachedRegex->captureCount; } cachedRegex = NULL; OSSpinLockUnlock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. if(captureCountPtr != NULL) { *captureCountPtr = captureCount; } if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } return(gotCachedRegex); } #pragma mark Functions used for clearing and releasing resources for various internal data structures static void rkl_clearStringCache(void) { RKLCAbortAssert(rkl_cacheSpinLock != (OSSpinLock)0); rkl_lastCachedRegex = NULL; NSUInteger x = 0UL; for(x = 0UL; x < _RKL_SCRATCH_BUFFERS; x++) { if(rkl_scratchBuffer[x] != NULL) { rkl_scratchBuffer[x] = rkl_free(&rkl_scratchBuffer[x]); } } for(x = 0UL; x < _RKL_REGEX_CACHE_LINES; x++) { rkl_clearCachedRegex(&rkl_cachedRegexes[x]); } for(x = 0UL; x < _RKL_LRU_CACHE_SET_WAYS; x++) { rkl_clearBuffer(&rkl_lruFixedBuffer[x], 0UL); rkl_clearBuffer(&rkl_lruDynamicBuffer[x], 1UL); } } static void rkl_clearBuffer(RKLBuffer *buffer, NSUInteger freeDynamicBuffer) { RKLCAbortAssert(buffer != NULL); if(RKL_EXPECTED(buffer == NULL, 0L)) { return; } if(RKL_EXPECTED(freeDynamicBuffer == 1UL, 0L) && RKL_EXPECTED(buffer->uniChar != NULL, 1L)) { RKL_STRONG_REF void * RKL_GC_VOLATILE p = (RKL_STRONG_REF void * RKL_GC_VOLATILE)buffer->uniChar; buffer->uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_free(&p); } if(RKL_EXPECTED(buffer->string != NULL, 1L)) { CFRelease((CFTypeRef)buffer->string); buffer->string = NULL; } buffer->length = 0L; buffer->hash = 0UL; } static void rkl_clearCachedRegex(RKLCachedRegex *cachedRegex) { RKLCAbortAssert(cachedRegex != NULL); if(RKL_EXPECTED(cachedRegex == NULL, 0L)) { return; } rkl_clearCachedRegexSetTo(cachedRegex); if(rkl_lastCachedRegex == cachedRegex) { rkl_lastCachedRegex = NULL; } if(cachedRegex->icu_regex != NULL) { RKL_ICU_FUNCTION_APPEND(uregex_close)(cachedRegex->icu_regex); cachedRegex->icu_regex = NULL; cachedRegex->captureCount = -1L; } if(cachedRegex->regexString != NULL) { CFRelease((CFTypeRef)cachedRegex->regexString); cachedRegex->regexString = NULL; cachedRegex->options = 0U; cachedRegex->regexHash = 0UL; } } static void rkl_clearCachedRegexSetTo(RKLCachedRegex *cachedRegex) { RKLCAbortAssert(cachedRegex != NULL); if(RKL_EXPECTED(cachedRegex == NULL, 0L)) { return; } if(RKL_EXPECTED(cachedRegex->icu_regex != NULL, 1L)) { int32_t status = 0; RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex->icu_regex, &rkl_emptyUniCharString[0], 0, &status); } if(RKL_EXPECTED(cachedRegex->setToString != NULL, 1L)) { CFRelease((CFTypeRef)cachedRegex->setToString); cachedRegex->setToString = NULL; } cachedRegex->lastFindRange = cachedRegex->lastMatchRange = cachedRegex->setToRange = NSNotFoundRange; cachedRegex->setToIsImmutable = cachedRegex->setToNeedsConversion = 0U; cachedRegex->setToUniChar = NULL; cachedRegex->setToHash = 0UL; cachedRegex->setToLength = 0L; cachedRegex->buffer = NULL; } #pragma mark Internal functions used to implement NSException and NSError functionality and userInfo NSDictionaries // Helps to keep things tidy. #define addKeyAndObject(objs, keys, i, k, o) ({id _o=(o), _k=(k); if((_o != NULL) && (_k != NULL)) { objs[i] = _o; keys[i] = _k; i++; } }) static NSDictionary *rkl_userInfoDictionary(RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, ...) { va_list varArgsList; va_start(varArgsList, enumerationOptions); if(regexString == NULL) { regexString = @"<NULL regex>"; } id objects[64], keys[64]; NSUInteger count = 0UL; NSString * RKL_GC_VOLATILE errorNameString = [NSString stringWithUTF8String:RKL_ICU_FUNCTION_APPEND(u_errorName)(status)]; addKeyAndObject(objects, keys, count, RKLICURegexRegexErrorKey, regexString); addKeyAndObject(objects, keys, count, RKLICURegexRegexOptionsErrorKey, [NSNumber numberWithUnsignedInt:options]); addKeyAndObject(objects, keys, count, RKLICURegexErrorCodeErrorKey, [NSNumber numberWithInt:status]); addKeyAndObject(objects, keys, count, RKLICURegexErrorNameErrorKey, errorNameString); if(matchString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexSubjectStringErrorKey, matchString); } if((userInfoOptions & RKLUserInfoSubjectRange) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexSubjectRangeErrorKey, [NSValue valueWithRange:matchRange]); } if(replacementString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacementStringErrorKey, replacementString); } if(replacedString != NULL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacedStringErrorKey, replacedString); } if((userInfoOptions & RKLUserInfoReplacedCount) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexReplacedCountErrorKey, [NSNumber numberWithInteger:replacedCount]); } if((userInfoOptions & RKLUserInfoRegexEnumerationOptions) != 0UL) { addKeyAndObject(objects, keys, count, RKLICURegexEnumerationOptionsErrorKey, [NSNumber numberWithUnsignedInteger:enumerationOptions]); } if((parseError != NULL) && (parseError->line != -1)) { NSString *preContextString = [NSString stringWithCharacters:&parseError->preContext[0] length:(NSUInteger)RKL_ICU_FUNCTION_APPEND(u_strlen)(&parseError->preContext[0])]; NSString *postContextString = [NSString stringWithCharacters:&parseError->postContext[0] length:(NSUInteger)RKL_ICU_FUNCTION_APPEND(u_strlen)(&parseError->postContext[0])]; addKeyAndObject(objects, keys, count, RKLICURegexLineErrorKey, [NSNumber numberWithInt:parseError->line]); addKeyAndObject(objects, keys, count, RKLICURegexOffsetErrorKey, [NSNumber numberWithInt:parseError->offset]); addKeyAndObject(objects, keys, count, RKLICURegexPreContextErrorKey, preContextString); addKeyAndObject(objects, keys, count, RKLICURegexPostContextErrorKey, postContextString); addKeyAndObject(objects, keys, count, @"NSLocalizedFailureReason", ([NSString stringWithFormat:@"The error %@ occurred at line %d, column %d: %@<<HERE>>%@", errorNameString, parseError->line, parseError->offset, preContextString, postContextString])); } else { addKeyAndObject(objects, keys, count, @"NSLocalizedFailureReason", ([NSString stringWithFormat:@"The error %@ occurred.", errorNameString])); } while(count < 62UL) { id obj = va_arg(varArgsList, id), key = va_arg(varArgsList, id); if((obj != NULL) && (key != NULL)) { addKeyAndObject(objects, keys, count, key, obj); } else { break; } } va_end(varArgsList); return([NSDictionary dictionaryWithObjects:&objects[0] forKeys:&keys[0] count:count]); } static NSError *rkl_makeNSError(RKLUserInfoOptions userInfoOptions, NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status, NSString *matchString, NSRange matchRange, NSString *replacementString, NSString *replacedString, NSInteger replacedCount, RKLRegexEnumerationOptions enumerationOptions, NSString *errorDescription) { if(errorDescription == NULL) { errorDescription = (status == U_ZERO_ERROR) ? @"No description of this error is available." : [NSString stringWithFormat:@"ICU regular expression error #%d, %s.", status, RKL_ICU_FUNCTION_APPEND(u_errorName)(status)]; } return([NSError errorWithDomain:RKLICURegexErrorDomain code:(NSInteger)status userInfo:rkl_userInfoDictionary(userInfoOptions, regexString, options, parseError, status, matchString, matchRange, replacementString, replacedString, replacedCount, enumerationOptions, errorDescription, @"NSLocalizedDescription", NULL)]); } static NSException *rkl_NSExceptionForRegex(NSString *regexString, RKLRegexOptions options, const UParseError *parseError, int32_t status) { return([NSException exceptionWithName:RKLICURegexException reason:[NSString stringWithFormat:@"ICU regular expression error #%d, %s.", status, RKL_ICU_FUNCTION_APPEND(u_errorName)(status)] userInfo:rkl_userInfoDictionary((RKLUserInfoOptions)RKLUserInfoNone, regexString, options, parseError, status, NULL, NSNotFoundRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, NULL)]); } static NSDictionary *rkl_makeAssertDictionary(const char *function, const char *file, int line, NSString *format, ...) { va_list varArgsList; va_start(varArgsList, format); NSString * RKL_GC_VOLATILE formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; va_end(varArgsList); NSString * RKL_GC_VOLATILE functionString = [NSString stringWithUTF8String:function], *fileString = [NSString stringWithUTF8String:file]; return([NSDictionary dictionaryWithObjectsAndKeys:formatString, @"description", functionString, @"function", fileString, @"file", [NSNumber numberWithInt:line], @"line", NSInternalInconsistencyException, @"exceptionName", NULL]); } static NSString *rkl_stringFromClassAndMethod(id object, SEL selector, NSString *format, ...) { va_list varArgsList; va_start(varArgsList, format); NSString * RKL_GC_VOLATILE formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; va_end(varArgsList); Class objectsClass = (object == NULL) ? NULL : [object class]; return([NSString stringWithFormat:@"*** %c[%@ %@]: %@", (object == objectsClass) ? '+' : '-', (objectsClass == NULL) ? @"<NULL>" : NSStringFromClass(objectsClass), (selector == NULL) ? @":NULL:" : NSStringFromSelector(selector), formatString]); } #ifdef _RKL_BLOCKS_ENABLED //////////// #pragma mark - #pragma mark Objective-C ^Blocks Support #pragma mark - //////////// // Prototypes static id rkl_performEnumerationUsingBlock(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, id matchString, NSRange matchRange, RKLBlockEnumerationOp blockEnumerationOp, RKLRegexEnumerationOptions enumerationOptions, NSInteger *replacedCountPtr, NSUInteger *errorFreePtr, NSError **error, void (^stringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop), NSString *(^replaceStringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop) ) RKL_NONNULL_ARGS(1,2,4,6); // This is an object meant for internal use only. It wraps and abstracts various functionality to simplify ^Blocks support. @interface RKLBlockEnumerationHelper : NSObject { @public RKLCachedRegex cachedRegex; RKLBuffer buffer; RKL_STRONG_REF void * RKL_GC_VOLATILE scratchBuffer[_RKL_SCRATCH_BUFFERS]; NSUInteger needToFreeBufferUniChar:1; } - (id)initWithRegex:(NSString *)initRegexString options:(RKLRegexOptions)initOptions string:(NSString *)initString range:(NSRange)initRange error:(NSError **)initError; @end @implementation RKLBlockEnumerationHelper - (id)initWithRegex:(NSString *)initRegexString options:(RKLRegexOptions)initOptions string:(NSString *)initString range:(NSRange)initRange error:(NSError **)initError { volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; int32_t status = U_ZERO_ERROR; id exception = NULL; RKLCachedRegex *retrievedCachedRegex = NULL; #ifdef _RKL_DTRACE_ENABLED NSUInteger thisDTraceEventID = 0UL; unsigned int lookupResultFlags = 0U; #endif if(RKL_EXPECTED((self = [super init]) == NULL, 0L)) { goto errorExit; } RKLCDelayedAssert((initRegexString != NULL) && (initString != NULL), &exception, errorExit); // IMPORTANT! Once we have obtained the lock, code MUST exit via 'goto exitNow;' to unlock the lock! NO EXCEPTIONS! // ---------- OSSpinLockLock(&rkl_cacheSpinLock); // Grab the lock and get cache entry. rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; rkl_dtrace_incrementAndGetEventID(thisDTraceEventID); if(RKL_EXPECTED((retrievedCachedRegex = rkl_getCachedRegex(initRegexString, initOptions, initError, &exception)) == NULL, 0L)) { goto exitNow; } RKLCDelayedAssert(((retrievedCachedRegex >= rkl_cachedRegexes) && ((retrievedCachedRegex - &rkl_cachedRegexes[0]) < (ssize_t)_RKL_REGEX_CACHE_LINES)) && (retrievedCachedRegex != NULL) && (retrievedCachedRegex->icu_regex != NULL) && (retrievedCachedRegex->regexString != NULL) && (retrievedCachedRegex->captureCount >= 0L) && (retrievedCachedRegex == rkl_lastCachedRegex), &exception, exitNow); if(RKL_EXPECTED(retrievedCachedRegex == NULL, 0L) || RKL_EXPECTED(status > U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto exitNow; } if(RKL_EXPECTED((cachedRegex.icu_regex = RKL_ICU_FUNCTION_APPEND(uregex_clone)(retrievedCachedRegex->icu_regex, &status)) == NULL, 0L) || RKL_EXPECTED(status != U_ZERO_ERROR, 0L)) { goto exitNow; } if(RKL_EXPECTED((cachedRegex.regexString = (CFStringRef)CFRetain((CFTypeRef)retrievedCachedRegex->regexString)) == NULL, 0L)) { goto exitNow; } cachedRegex.options = initOptions; cachedRegex.captureCount = retrievedCachedRegex->captureCount; cachedRegex.regexHash = retrievedCachedRegex->regexHash; RKLCDelayedAssert((cachedRegex.icu_regex != NULL) && (cachedRegex.regexString != NULL) && (cachedRegex.captureCount >= 0L), &exception, exitNow); exitNow: if((rkl_cacheSpinLockStatus & RKLLockedCacheSpinLock) != 0UL) { // In case we arrive at exitNow: without obtaining the rkl_cacheSpinLock. OSSpinLockUnlock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. } if(RKL_EXPECTED(self == NULL, 0L) || RKL_EXPECTED(retrievedCachedRegex == NULL, 0L) || RKL_EXPECTED(cachedRegex.icu_regex == NULL, 0L) || RKL_EXPECTED(status != U_ZERO_ERROR, 0L) || RKL_EXPECTED(exception != NULL, 0L)) { goto errorExit; } retrievedCachedRegex = NULL; // Since we no longer hold the lock, ensure that nothing accesses the retrieved cache regex after this point. rkl_dtrace_addLookupFlag(lookupResultFlags, RKLEnumerationBufferLookupFlag); if(RKL_EXPECTED((buffer.string = CFStringCreateCopy(NULL, (CFStringRef)initString)) == NULL, 0L)) { goto errorExit; } buffer.hash = CFHash((CFTypeRef)buffer.string); buffer.length = CFStringGetLength(buffer.string); if((buffer.uniChar = (UniChar *)CFStringGetCharactersPtr(buffer.string)) == NULL) { rkl_dtrace_addLookupFlag(lookupResultFlags, RKLConversionRequiredLookupFlag); if(RKL_EXPECTED((buffer.uniChar = (RKL_STRONG_REF UniChar * RKL_GC_VOLATILE)rkl_realloc((RKL_STRONG_REF void ** RKL_GC_VOLATILE)&buffer.uniChar, ((size_t)buffer.length * sizeof(UniChar)), 0UL)) == NULL, 0L)) { goto errorExit; } // Resize the buffer. needToFreeBufferUniChar = rkl_collectingEnabled() ? 0U : 1U; CFStringGetCharacters(buffer.string, CFMakeRange(0L, buffer.length), (UniChar *)buffer.uniChar); // Convert to a UTF16 string. } if(RKL_EXPECTED((cachedRegex.setToString = (CFStringRef)CFRetain((CFTypeRef)buffer.string)) == NULL, 0L)) { goto errorExit; } cachedRegex.setToHash = buffer.hash; cachedRegex.setToLength = buffer.length; cachedRegex.setToUniChar = buffer.uniChar; cachedRegex.buffer = &buffer; RKLCDelayedAssert((cachedRegex.icu_regex != NULL) && (cachedRegex.setToUniChar != NULL) && (cachedRegex.setToLength < INT_MAX) && (NSMaxRange(initRange) <= (NSUInteger)cachedRegex.setToLength) && (NSMaxRange(initRange) < INT_MAX), &exception, errorExit); cachedRegex.lastFindRange = cachedRegex.lastMatchRange = NSNotFoundRange; cachedRegex.setToRange = initRange; RKL_ICU_FUNCTION_APPEND(uregex_setText)(cachedRegex.icu_regex, cachedRegex.setToUniChar + cachedRegex.setToRange.location, (int32_t)cachedRegex.setToRange.length, &status); if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L)) { goto errorExit; } rkl_dtrace_addLookupFlag(lookupResultFlags, RKLSetTextLookupFlag); rkl_dtrace_utf16ConversionCacheWithEventID(thisDTraceEventID, lookupResultFlags, initString, cachedRegex.setToRange.location, cachedRegex.setToRange.length, cachedRegex.setToLength); return(self); errorExit: if(RKL_EXPECTED(self != NULL, 1L)) { [self autorelease]; } if(RKL_EXPECTED(status > U_ZERO_ERROR, 0L) && RKL_EXPECTED(exception == NULL, 0L)) { exception = rkl_NSExceptionForRegex(initRegexString, initOptions, NULL, status); } // If we had a problem, prepare an exception to be thrown. if(RKL_EXPECTED(status < U_ZERO_ERROR, 0L) && (initError != NULL)) { *initError = rkl_makeNSError((RKLUserInfoOptions)RKLUserInfoNone, initRegexString, initOptions, NULL, status, initString, initRange, NULL, NULL, 0L, (RKLRegexEnumerationOptions)RKLRegexEnumerationNoOptions, @"The ICU library returned an unexpected error."); } if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } return(NULL); } #ifdef __OBJC_GC__ - (void)finalize { rkl_clearCachedRegex(&cachedRegex); rkl_clearBuffer(&buffer, (needToFreeBufferUniChar != 0U) ? 1LU : 0LU); NSUInteger tmpIdx = 0UL; // The rkl_free() below is "probably" a no-op when GC is on, but better to be safe than sorry... for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(scratchBuffer[tmpIdx] != NULL, 0L)) { scratchBuffer[tmpIdx] = rkl_free(&scratchBuffer[tmpIdx]); } } [super finalize]; } #endif // __OBJC_GC__ - (void)dealloc { rkl_clearCachedRegex(&cachedRegex); rkl_clearBuffer(&buffer, (needToFreeBufferUniChar != 0U) ? 1LU : 0LU); NSUInteger tmpIdx = 0UL; for(tmpIdx = 0UL; tmpIdx < _RKL_SCRATCH_BUFFERS; tmpIdx++) { if(RKL_EXPECTED(scratchBuffer[tmpIdx] != NULL, 0L)) { scratchBuffer[tmpIdx] = rkl_free(&scratchBuffer[tmpIdx]); } } [super dealloc]; } @end // IMPORTANT! This code is critical path code. Because of this, it has been written for speed, not clarity. // ---------- // // Return value: BOOL. Per "Error Handling Programming Guide" wrt/ NSError, return NO on error / failure, and set *error to an NSError object. // // rkl_performEnumerationUsingBlock reference counted / manual memory management notes: // // When running using reference counting, rkl_performEnumerationUsingBlock() creates a CFMutableArray called autoreleaseArray, which is -autoreleased. // autoreleaseArray uses the rkl_transferOwnershipArrayCallBacks CFArray callbacks which do not perform a -retain/CFRetain() when objects are added, but do perform a -release/CFRelease() when an object is removed. // // A special class, RKLBlockEnumerationHelper, is used to manage the details of creating a private instantiation of the ICU regex (via uregex_clone()) and setting up the details of the UTF-16 buffer required by the ICU regex engine. // The instantiated RKLBlockEnumerationHelper is not autoreleased, but added to autoreleaseArray. When rkl_performEnumerationUsingBlock() exits, it calls CFArrayRemoveAllValues(autoreleaseArray), which empties the array. // This has the effect of immediately -releasing the instantiated RKLBlockEnumerationHelper object, and all the memory used to hold the ICU regex and UTF-16 conversion buffer. // This means the memory is reclaimed immediately and we do not have to wait until the autorelease pool pops. // // If we are performing a "string replacement" operation, we create a temporary NSMutableString named mutableReplacementString to hold the replaced strings results. mutableReplacementString is also added to autoreleaseArray so that it // can be properly released on an error. // // Temporary strings that are created during the enumeration of matches are added to autoreleaseArray. // The strings are added by doing a CFArrayReplaceValues(), which simultaneously releases the previous iterations temporary strings while adding the current iterations temporary strings to the array. // // autoreleaseArray always has a reference to any "live" and in use objects. If anything "Goes Wrong", at any point, for any reason (ie, exception is thrown), autoreleaseArray is in the current NSAutoreleasePool // and will automatically be released when that pool pops. This ensures that we don't leak anything even when things go seriously sideways. This also allows us to keep the total amount of memory in use // down to a minimum, which can be substantial if the user is enumerating a large string, for example a regex of '\w+' on a 500K+ text file. // // The only 'caveat' is that the user needs to -retain any strings that they want to use past the point at which their ^block returns. Logically, it is as if the following takes place: // // for(eachMatchOfRegexInStringToSearch) { // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // callUsersBlock(capturedCount, capturedStrings, capturedStringRanges, stop); // [pool release]; // } // // But in reality, no NSAutoreleasePool is created, it's all slight of hand done via the CFMutableArray autoreleaseArray. // // rkl_performEnumerationUsingBlock garbage collected / automatic memory management notes: // // When RegexKitLite is built with -fobjc-gc or -fobjc-gc-only, and (in the case of -fobjc-gc) RegexKitLite determines that GC is active at execution time, then rkl_performEnumerationUsingBlock essentially // skips all of the above reference counted autoreleaseArray stuff. // // rkl_performEnumerationUsingBlock and RKLRegexEnumerationReleaseStringReturnedByReplacementBlock notes // // Under reference counting, this enumeration option allows the user to return a non-autoreleased string, and then have RegexKitLite send the object a -release message once it's done with it. // The primary reason to do this is to immediately reclaim the memory used by the string holding the replacement text. // Just in case the user returns one of the strings we passed via capturedStrings[], we check to see if the string return by the block is any of the strings we created and passed via capturedStrings[]. // If it is one of our strings, we do not send the string a -release since that would over release it. It is assumed that the user will /NOT/ add a -retain to our strings in this case. // Under GC, RKLRegexEnumerationReleaseStringReturnedByReplacementBlock is ignored and no -release messages are sent. // #pragma mark Primary internal function that Objective-C ^Blocks related methods call to perform regular expression operations static id rkl_performEnumerationUsingBlock(id self, SEL _cmd, RKLRegexOp regexOp, NSString *regexString, RKLRegexOptions options, id matchString, NSRange matchRange, RKLBlockEnumerationOp blockEnumerationOp, RKLRegexEnumerationOptions enumerationOptions, NSInteger *replacedCountPtr, NSUInteger *errorFreePtr, NSError **error, void (^stringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop), NSString *(^replaceStringsAndRangesBlock)(NSInteger capturedCount, NSString * const capturedStrings[capturedCount], const NSRange capturedStringRanges[capturedCount], volatile BOOL * const stop)) { NSMutableArray * RKL_GC_VOLATILE autoreleaseArray = NULL; RKLBlockEnumerationHelper * RKL_GC_VOLATILE blockEnumerationHelper = NULL; NSMutableString * RKL_GC_VOLATILE mutableReplacementString = NULL; RKL_STRONG_REF UniChar * RKL_GC_VOLATILE blockEnumerationHelperUniChar = NULL; NSUInteger errorFree = NO; id exception = NULL, returnObject = NULL; CFRange autoreleaseReplaceRange = CFMakeRange(0L, 0L); int32_t status = U_ZERO_ERROR; RKLRegexOp maskedRegexOp = (regexOp & RKLMaskOp); volatile BOOL shouldStop = NO; NSInteger replacedCount = -1L; NSRange lastMatchedRange = NSNotFoundRange; NSUInteger stringU16Length = 0UL; BOOL performStringReplacement = (blockEnumerationOp == RKLBlockEnumerationReplaceOp) ? YES : NO; if((error != NULL) && (*error != NULL)) { *error = NULL; } if(RKL_EXPECTED(regexString == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The regular expression argument is NULL."); goto exitNow; } if(RKL_EXPECTED(matchString == NULL, 0L)) { exception = (id)RKL_EXCEPTION(NSInternalInconsistencyException, @"The match string argument is NULL."); goto exitNow; } if((((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) != 0UL) && ((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL)) || (((enumerationOptions & RKLRegexEnumerationReleaseStringReturnedByReplacementBlock) != 0UL) && (blockEnumerationOp != RKLBlockEnumerationReplaceOp)) || ((enumerationOptions & (~((RKLRegexEnumerationOptions)(RKLRegexEnumerationCapturedStringsNotRequired | RKLRegexEnumerationReleaseStringReturnedByReplacementBlock | RKLRegexEnumerationFastCapturedStringsXXX)))) != 0UL)) { exception = (id)RKL_EXCEPTION(NSInvalidArgumentException, @"The RKLRegexEnumerationOptions argument is not valid."); goto exitNow; } stringU16Length = (NSUInteger)CFStringGetLength((CFStringRef)matchString); if(RKL_EXPECTED(matchRange.length == NSUIntegerMax, 1L)) { matchRange.length = stringU16Length; } // For convenience. if(RKL_EXPECTED(stringU16Length < NSMaxRange(matchRange), 0L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"Range or index out of bounds."); goto exitNow; } if(RKL_EXPECTED(stringU16Length >= (NSUInteger)INT_MAX, 0L)) { exception = (id)RKL_EXCEPTION(NSRangeException, @"String length exceeds INT_MAX."); goto exitNow; } RKLCDelayedAssert((self != NULL) && (_cmd != NULL) && ((blockEnumerationOp == RKLBlockEnumerationMatchOp) ? (((regexOp == RKLCapturesArrayOp) || (regexOp == RKLSplitOp)) && (stringsAndRangesBlock != NULL) && (replaceStringsAndRangesBlock == NULL)) : 1) && ((blockEnumerationOp == RKLBlockEnumerationReplaceOp) ? ((regexOp == RKLCapturesArrayOp) && (stringsAndRangesBlock == NULL) && (replaceStringsAndRangesBlock != NULL)) : 1) , &exception, exitNow); if((rkl_collectingEnabled() == NO) && RKL_EXPECTED((autoreleaseArray = rkl_CFAutorelease(CFArrayCreateMutable(NULL, 0L, &rkl_transferOwnershipArrayCallBacks))) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of Core Foundation object can be safely ignored. if(RKL_EXPECTED((blockEnumerationHelper = [[RKLBlockEnumerationHelper alloc] initWithRegex:regexString options:options string:matchString range:matchRange error:error]) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of blockEnumerationHelper can be safely ignored. if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, blockEnumerationHelper); autoreleaseReplaceRange.location++; } // We do not autorelease blockEnumerationHelper, but instead add it to autoreleaseArray. if(performStringReplacement == YES) { if(RKL_EXPECTED((mutableReplacementString = [[NSMutableString alloc] init]) == NULL, 0L)) { goto exitNow; } // Warning about potential leak of mutableReplacementString can be safely ignored. if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, mutableReplacementString); autoreleaseReplaceRange.location++; } // We do not autorelease mutableReplacementString, but instead add it to autoreleaseArray. } // RKLBlockEnumerationHelper creates an immutable copy of the string to match (matchString) which we reference via blockEnumerationHelperString. We use blockEnumerationHelperString when creating the captured strings from a match. // This protects us against the user mutating matchString while we are in the middle of enumerating matches. NSString * RKL_GC_VOLATILE blockEnumerationHelperString = (NSString *)blockEnumerationHelper->buffer.string, ** RKL_GC_VOLATILE capturedStrings = NULL, *emptyString = @""; CFMutableStringRef * RKL_GC_VOLATILE fastCapturedStrings = NULL; NSInteger captureCountBlockArgument = (blockEnumerationHelper->cachedRegex.captureCount + 1L); size_t capturedStringsCapacity = ((size_t)captureCountBlockArgument + 4UL); size_t capturedRangesCapacity = (((size_t)captureCountBlockArgument + 4UL) * 5UL); NSRange *capturedRanges = NULL; lastMatchedRange = NSMakeRange(matchRange.location, 0UL); blockEnumerationHelperUniChar = blockEnumerationHelper->buffer.uniChar; RKLCDelayedAssert((blockEnumerationHelperString != NULL) && (blockEnumerationHelperUniChar != NULL) && (captureCountBlockArgument > 0L) && (capturedStringsCapacity > 0UL) && (capturedRangesCapacity > 0UL), &exception, exitNow); if((capturedStrings = (NSString ** RKL_GC_VOLATILE)alloca(sizeof(NSString *) * capturedStringsCapacity)) == NULL) { goto exitNow; } // Space to hold the captured strings from a match. if((capturedRanges = (NSRange *) alloca(sizeof(NSRange) * capturedRangesCapacity)) == NULL) { goto exitNow; } // Space to hold the NSRanges of the captured strings from a match. #ifdef NS_BLOCK_ASSERTIONS { // Initialize the padded capturedStrings and capturedRanges to values that should tickle a fault if they are ever used. size_t idx = 0UL; for(idx = captureCountBlockArgument; idx < capturedStringsCapacity; idx++) { capturedStrings[idx] = (NSString *)RKLIllegalPointer; } for(idx = captureCountBlockArgument; idx < capturedRangesCapacity; idx++) { capturedRanges[idx] = RKLIllegalRange; } } #else { // Initialize all of the capturedStrings and capturedRanges to values that should tickle a fault if they are ever used. size_t idx = 0UL; for(idx = 0UL; idx < capturedStringsCapacity; idx++) { capturedStrings[idx] = (NSString *)RKLIllegalPointer; } for(idx = 0UL; idx < capturedRangesCapacity; idx++) { capturedRanges[idx] = RKLIllegalRange; } } #endif if((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL) { RKLCDelayedAssert(((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) == 0UL), &exception, exitNow); size_t idx = 0UL; if((fastCapturedStrings = (CFMutableStringRef * RKL_GC_VOLATILE)alloca(sizeof(NSString *) * capturedStringsCapacity)) == NULL) { goto exitNow; } // Space to hold the "fast" captured strings from a match. for(idx = 0UL; idx < (size_t)captureCountBlockArgument; idx++) { if((fastCapturedStrings[idx] = CFStringCreateMutableWithExternalCharactersNoCopy(NULL, NULL, 0L, 0L, kCFAllocatorNull)) == NULL) { goto exitNow; } if(autoreleaseArray != NULL) { CFArrayAppendValue((CFMutableArrayRef)autoreleaseArray, fastCapturedStrings[idx]); autoreleaseReplaceRange.location++; } // We do not autorelease mutableReplacementString, but instead add it to autoreleaseArray. capturedStrings[idx] = (NSString *)fastCapturedStrings[idx]; } } RKLFindAll findAll = rkl_makeFindAll(capturedRanges, matchRange, (NSInteger)capturedRangesCapacity, (capturedRangesCapacity * sizeof(NSRange)), 0UL, &blockEnumerationHelper->scratchBuffer[0], &blockEnumerationHelper->scratchBuffer[1], &blockEnumerationHelper->scratchBuffer[2], &blockEnumerationHelper->scratchBuffer[3], &blockEnumerationHelper->scratchBuffer[4], 0L, 0L, 1L); NSString ** RKL_GC_VOLATILE capturedStringsBlockArgument = NULL; // capturedStringsBlockArgument is what we pass to the 'capturedStrings[]' argument of the users ^block. Will pass NULL if the user doesn't want the captured strings created automatically. if((enumerationOptions & RKLRegexEnumerationCapturedStringsNotRequired) == 0UL) { capturedStringsBlockArgument = capturedStrings; } // If the user wants the captured strings automatically created, set to capturedStrings. replacedCount = 0L; while(RKL_EXPECTED(rkl_findRanges(&blockEnumerationHelper->cachedRegex, regexOp, &findAll, &exception, &status) == NO, 1L) && RKL_EXPECTED(findAll.found > 0L, 1L) && RKL_EXPECTED(exception == NULL, 1L) && RKL_EXPECTED(status == U_ZERO_ERROR, 1L)) { if(performStringReplacement == YES) { NSUInteger lastMatchedMaxLocation = (lastMatchedRange.location + lastMatchedRange.length); NSRange previousUnmatchedRange = NSMakeRange(lastMatchedMaxLocation, findAll.ranges[0].location - lastMatchedMaxLocation); RKLCDelayedAssert((NSMaxRange(previousUnmatchedRange) <= stringU16Length) && (NSRangeInsideRange(previousUnmatchedRange, matchRange) == YES), &exception, exitNow); if(RKL_EXPECTED(previousUnmatchedRange.length > 0UL, 1L)) { CFStringAppendCharacters((CFMutableStringRef)mutableReplacementString, blockEnumerationHelperUniChar + previousUnmatchedRange.location, (CFIndex)previousUnmatchedRange.length); } } findAll.found -= findAll.addedSplitRanges; NSInteger passCaptureCountBlockArgument = ((findAll.found == 0L) && (findAll.addedSplitRanges == 1L) && (maskedRegexOp == RKLSplitOp)) ? 1L : findAll.found, capturedStringsIdx = passCaptureCountBlockArgument; RKLCDelayedHardAssert(passCaptureCountBlockArgument <= captureCountBlockArgument, &exception, exitNow); if(capturedStringsBlockArgument != NULL) { // Only create the captured strings if the user has requested them. BOOL hadError = NO; // Loop over all the strings rkl_findRanges found. If rkl_CreateStringWithSubstring() returns NULL due to an error, set returnBool to NO, and break out of the for() loop. for(capturedStringsIdx = 0L; capturedStringsIdx < passCaptureCountBlockArgument; capturedStringsIdx++) { RKLCDelayedHardAssert(capturedStringsIdx < captureCountBlockArgument, &exception, exitNow); if((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) != 0UL) { // Analyzer report of "Dereference of null pointer" can be safely ignored for the next line. Bug filed: http://llvm.org/bugs/show_bug.cgi?id=6150 CFStringSetExternalCharactersNoCopy(fastCapturedStrings[capturedStringsIdx], &blockEnumerationHelperUniChar[findAll.ranges[capturedStringsIdx].location], (CFIndex)findAll.ranges[capturedStringsIdx].length, (CFIndex)findAll.ranges[capturedStringsIdx].length); } else { if((capturedStrings[capturedStringsIdx] = (findAll.ranges[capturedStringsIdx].length == 0UL) ? emptyString : rkl_CreateStringWithSubstring(blockEnumerationHelperString, findAll.ranges[capturedStringsIdx])) == NULL) { hadError = YES; break; } } } if(((enumerationOptions & RKLRegexEnumerationFastCapturedStringsXXX) == 0UL) && RKL_EXPECTED(autoreleaseArray != NULL, 1L)) { CFArrayReplaceValues((CFMutableArrayRef)autoreleaseArray, autoreleaseReplaceRange, (const void **)capturedStrings, capturedStringsIdx); autoreleaseReplaceRange.length = capturedStringsIdx; } // Add to autoreleaseArray all the strings the for() loop created. if(RKL_EXPECTED(hadError == YES, 0L)) { goto exitNow; } // hadError == YES will be set if rkl_CreateStringWithSubstring() returned NULL. } // For safety, set any capturedRanges and capturedStrings up to captureCountBlockArgument + 1 to values that indicate that they are not valid. // These values are chosen such that they should tickle any misuse by users. // capturedStringsIdx is initialized to passCaptureCountBlockArgument, but if capturedStringsBlockArgument != NULL, it is reset to 0 by the loop that creates strings. // If the loop that creates strings has an error, execution should transfer to exitNow and this will never get run. // Again, this is for safety for users that do not check the passed block argument 'captureCount' and instead depend on something like [regex captureCount]. for(; capturedStringsIdx < captureCountBlockArgument + 1L; capturedStringsIdx++) { RKLCDelayedAssert((capturedStringsIdx < (NSInteger)capturedStringsCapacity) && (capturedStringsIdx < (NSInteger)capturedRangesCapacity), &exception, exitNow); capturedRanges[capturedStringsIdx] = RKLIllegalRange; capturedStrings[capturedStringsIdx] = (NSString *)RKLIllegalPointer; } RKLCDelayedAssert((passCaptureCountBlockArgument > 0L) && (NSMaxRange(capturedRanges[0]) <= stringU16Length) && (capturedRanges[0].location < NSIntegerMax) && (capturedRanges[0].length < NSIntegerMax), &exception, exitNow); switch(blockEnumerationOp) { case RKLBlockEnumerationMatchOp: stringsAndRangesBlock(passCaptureCountBlockArgument, capturedStringsBlockArgument, capturedRanges, &shouldStop); break; case RKLBlockEnumerationReplaceOp: { NSString *blockReturnedReplacementString = replaceStringsAndRangesBlock(passCaptureCountBlockArgument, capturedStringsBlockArgument, capturedRanges, &shouldStop); if(RKL_EXPECTED(blockReturnedReplacementString != NULL, 1L)) { CFStringAppend((CFMutableStringRef)mutableReplacementString, (CFStringRef)blockReturnedReplacementString); BOOL shouldRelease = (((enumerationOptions & RKLRegexEnumerationReleaseStringReturnedByReplacementBlock) != 0UL) && (capturedStringsBlockArgument != NULL) && (rkl_collectingEnabled() == NO)) ? YES : NO; if(shouldRelease == YES) { NSInteger idx = 0L; for(idx = 0L; idx < passCaptureCountBlockArgument; idx++) { if(capturedStrings[idx] == blockReturnedReplacementString) { shouldRelease = NO; break; } } } if(shouldRelease == YES) { [blockReturnedReplacementString release]; } } } break; default: exception = RKLCAssertDictionary(@"Unknown blockEnumerationOp code."); goto exitNow; break; } replacedCount++; findAll.addedSplitRanges = 0L; // rkl_findRanges() expects findAll.addedSplitRanges to be 0 on entry. findAll.found = 0L; // rkl_findRanges() expects findAll.found to be 0 on entry. findAll.findInRange = findAll.remainingRange; // Ask rkl_findRanges() to search the part of the string after the current match. lastMatchedRange = findAll.ranges[0]; if(RKL_EXPECTED(shouldStop != NO, 0L)) { break; } } errorFree = YES; exitNow: if(RKL_EXPECTED(errorFree == NO, 0L)) { replacedCount = -1L; } if((blockEnumerationOp == RKLBlockEnumerationReplaceOp) && RKL_EXPECTED(errorFree == YES, 1L)) { RKLCDelayedAssert(replacedCount >= 0L, &exception, exitNow2); if(RKL_EXPECTED(replacedCount == 0UL, 0L)) { RKLCDelayedAssert((blockEnumerationHelper != NULL) && (blockEnumerationHelper->buffer.string != NULL), &exception, exitNow2); returnObject = rkl_CreateStringWithSubstring((id)blockEnumerationHelper->buffer.string, matchRange); if(rkl_collectingEnabled() == NO) { returnObject = rkl_CFAutorelease(returnObject); } } else { NSUInteger lastMatchedMaxLocation = (lastMatchedRange.location + lastMatchedRange.length); NSRange previousUnmatchedRange = NSMakeRange(lastMatchedMaxLocation, NSMaxRange(matchRange) - lastMatchedMaxLocation); RKLCDelayedAssert((NSMaxRange(previousUnmatchedRange) <= stringU16Length) && (NSRangeInsideRange(previousUnmatchedRange, matchRange) == YES), &exception, exitNow2); if(RKL_EXPECTED(previousUnmatchedRange.length > 0UL, 1L)) { CFStringAppendCharacters((CFMutableStringRef)mutableReplacementString, blockEnumerationHelperUniChar + previousUnmatchedRange.location, (CFIndex)previousUnmatchedRange.length); } returnObject = rkl_CFAutorelease(CFStringCreateCopy(NULL, (CFStringRef)mutableReplacementString)); // Warning about potential leak of Core Foundation object can be safely ignored. } } #ifndef NS_BLOCK_ASSERTIONS exitNow2: #endif // NS_BLOCK_ASSERTIONS if(RKL_EXPECTED(autoreleaseArray != NULL, 1L)) { CFArrayRemoveAllValues((CFMutableArrayRef)autoreleaseArray); } // Causes blockEnumerationHelper to be released immediately, freeing all of its resources (such as a large UTF-16 conversion buffer). if(RKL_EXPECTED(exception != NULL, 0L)) { rkl_handleDelayedAssert(self, _cmd, exception); } // If there is an exception, throw it at this point. if(((errorFree == NO) || ((errorFree == YES) && (returnObject == NULL))) && (error != NULL) && (*error == NULL)) { RKLUserInfoOptions userInfoOptions = (RKLUserInfoSubjectRange | RKLUserInfoRegexEnumerationOptions); NSString *replacedString = NULL; if(blockEnumerationOp == RKLBlockEnumerationReplaceOp) { userInfoOptions |= RKLUserInfoReplacedCount; if(RKL_EXPECTED(errorFree == YES, 1L)) { replacedString = returnObject; } } *error = rkl_makeNSError(userInfoOptions, regexString, options, NULL, status, (blockEnumerationHelper != NULL) ? (blockEnumerationHelper->buffer.string != NULL) ? (NSString *)blockEnumerationHelper->buffer.string : matchString : matchString, matchRange, NULL, replacedString, replacedCount, enumerationOptions, @"An unexpected error occurred."); } if(replacedCountPtr != NULL) { *replacedCountPtr = replacedCount; } if(errorFreePtr != NULL) { *errorFreePtr = errorFree; } return(returnObject); } // The two warnings about potential leaks can be safely ignored. #endif // _RKL_BLOCKS_ENABLED //////////// #pragma mark - #pragma mark Objective-C Public Interface #pragma mark - //////////// @implementation NSString (RegexKitLiteAdditions) #pragma mark +clearStringCache + (void)RKL_METHOD_PREPEND(clearStringCache) { volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; OSSpinLockLock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; rkl_clearStringCache(); OSSpinLockUnlock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. } #pragma mark +captureCountForRegex: + (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex { NSInteger captureCount = -1L; rkl_isRegexValid(self, _cmd, regex, RKLNoOptions, &captureCount, NULL); return(captureCount); } + (NSInteger)RKL_METHOD_PREPEND(captureCountForRegex):(NSString *)regex options:(RKLRegexOptions)options error:(NSError **)error { NSInteger captureCount = -1L; rkl_isRegexValid(self, _cmd, regex, options, &captureCount, error); return(captureCount); } #pragma mark -captureCount: - (NSInteger)RKL_METHOD_PREPEND(captureCount) { NSInteger captureCount = -1L; rkl_isRegexValid(self, _cmd, self, RKLNoOptions, &captureCount, NULL); return(captureCount); } - (NSInteger)RKL_METHOD_PREPEND(captureCountWithOptions):(RKLRegexOptions)options error:(NSError **)error { NSInteger captureCount = -1L; rkl_isRegexValid(self, _cmd, self, options, &captureCount, error); return(captureCount); } #pragma mark -componentsSeparatedByRegex: - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex { NSRange range = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex range:(NSRange)range { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(componentsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); } #pragma mark -isMatchedByRegex: - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex { NSRange result = NSNotFoundRange, range = NSMaxiumRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); return((result.location == (NSUInteger)NSNotFound) ? NO : YES); } - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex inRange:(NSRange)range { NSRange result = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); return((result.location == (NSUInteger)NSNotFound) ? NO : YES); } - (BOOL)RKL_METHOD_PREPEND(isMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error { NSRange result = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, 0L, self, &range, NULL, error, &result, 0UL, NULL, NULL); return((result.location == (NSUInteger)NSNotFound) ? NO : YES); } #pragma mark -isRegexValid - (BOOL)RKL_METHOD_PREPEND(isRegexValid) { return(rkl_isRegexValid(self, _cmd, self, RKLNoOptions, NULL, NULL) == 1UL ? YES : NO); } - (BOOL)RKL_METHOD_PREPEND(isRegexValidWithOptions):(RKLRegexOptions)options error:(NSError **)error { return(rkl_isRegexValid(self, _cmd, self, options, NULL, error) == 1UL ? YES : NO); } #pragma mark -flushCachedRegexData - (void)RKL_METHOD_PREPEND(flushCachedRegexData) { volatile NSUInteger RKL_CLEANUP(rkl_cleanup_cacheSpinLockStatus) rkl_cacheSpinLockStatus = 0UL; CFIndex selfLength = CFStringGetLength((CFStringRef)self); CFHashCode selfHash = CFHash((CFTypeRef)self); OSSpinLockLock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLLockedCacheSpinLock; rkl_dtrace_incrementEventID(); NSUInteger idx; for(idx = 0UL; idx < _RKL_REGEX_CACHE_LINES; idx++) { RKLCachedRegex *cachedRegex = &rkl_cachedRegexes[idx]; if((cachedRegex->setToString != NULL) && ( (cachedRegex->setToString == (CFStringRef)self) || ((cachedRegex->setToLength == selfLength) && (cachedRegex->setToHash == selfHash)) ) ) { rkl_clearCachedRegexSetTo(cachedRegex); } } for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { RKLBuffer *buffer = &rkl_lruFixedBuffer[idx]; if((buffer->string != NULL) && ((buffer->string == (CFStringRef)self) || ((buffer->length == selfLength) && (buffer->hash == selfHash)))) { rkl_clearBuffer(buffer, 0UL); } } for(idx = 0UL; idx < _RKL_LRU_CACHE_SET_WAYS; idx++) { RKLBuffer *buffer = &rkl_lruDynamicBuffer[idx]; if((buffer->string != NULL) && ((buffer->string == (CFStringRef)self) || ((buffer->length == selfLength) && (buffer->hash == selfHash)))) { rkl_clearBuffer(buffer, 0UL); } } OSSpinLockUnlock(&rkl_cacheSpinLock); rkl_cacheSpinLockStatus |= RKLUnlockedCacheSpinLock; // Warning about rkl_cacheSpinLockStatus never being read can be safely ignored. } #pragma mark -rangeOfRegex: - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex { NSRange result = NSNotFoundRange, range = NSMaxiumRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); return(result); } - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex capture:(NSInteger)capture { NSRange result = NSNotFoundRange, range = NSMaxiumRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, capture, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); return(result); } - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex inRange:(NSRange)range { NSRange result = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &result, 0UL, NULL, NULL); return(result); } - (NSRange)RKL_METHOD_PREPEND(rangeOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error { NSRange result = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, capture, self, &range, NULL, error, &result, 0UL, NULL, NULL); return(result); } #pragma mark -stringByMatching: - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex { NSRange matchedRange = NSNotFoundRange, range = NSMaxiumRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. } // Warning about potential leak can be safely ignored. - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex capture:(NSInteger)capture { NSRange matchedRange = NSNotFoundRange, range = NSMaxiumRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, capture, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. } // Warning about potential leak can be safely ignored. - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex inRange:(NSRange)range { NSRange matchedRange = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, &matchedRange, 0UL, NULL, NULL); return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. } // Warning about potential leak can be safely ignored. - (NSString *)RKL_METHOD_PREPEND(stringByMatching):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range capture:(NSInteger)capture error:(NSError **)error { NSRange matchedRange = NSNotFoundRange; rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLRangeOp, regex, options, capture, self, &range, NULL, error, &matchedRange, 0UL, NULL, NULL); return((matchedRange.location == (NSUInteger)NSNotFound) ? NULL : rkl_CFAutorelease(CFStringCreateWithSubstring(NULL, (CFStringRef)self, CFMakeRange(matchedRange.location, matchedRange.length)))); // Warning about potential leak can be safely ignored. } // Warning about potential leak can be safely ignored. #pragma mark -stringByReplacingOccurrencesOfRegex: - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement { NSRange searchRange = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, NULL, 0UL, NULL, NULL)); } - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, NULL, 0UL, NULL, NULL)); } - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLReplaceOp, regex, options, 0L, self, &searchRange, replacement, error, NULL, 0UL, NULL, NULL)); } #pragma mark -componentsMatchedByRegex: - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex { NSRange searchRange = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex capture:(NSInteger)capture { NSRange searchRange = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, capture, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex range:(NSRange)range { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(componentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range capture:(NSInteger)capture error:(NSError **)error { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfStringsOp, regex, options, capture, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); } #pragma mark -captureComponentsMatchedByRegex: - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex { NSRange searchRange = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(captureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); } #pragma mark -arrayOfCaptureComponentsMatchedByRegex: - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex { NSRange searchRange = NSMaxiumRange; return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex range:(NSRange)range { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, 0UL, NULL, NULL)); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfCaptureComponentsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLArrayOfCapturesOp | RKLSubcapturesArray), regex, options, 0L, self, &range, NULL, error, NULL, 0UL, NULL, NULL)); } #pragma mark -dictionaryByMatchingRegex: - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... { NSRange searchRange = NSMaxiumRange; id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... { id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... { id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList { return(rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList)); } - (NSDictionary *)RKL_METHOD_PREPEND(dictionaryByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLDictionaryOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, count, keys, captures)); } #pragma mark -arrayOfDictionariesByMatchingRegex: - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex withKeysAndCaptures:(id)firstKey, ... { NSRange searchRange = NSMaxiumRange; id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &searchRange, NULL, NULL, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex range:(NSRange)range withKeysAndCaptures:(id)firstKey, ... { id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, (RKLRegexOptions)RKLNoOptions, 0L, self, &range, NULL, NULL, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeysAndCaptures:(id)firstKey, ... { id returnObject = NULL; va_list varArgsList; va_start(varArgsList, firstKey); returnObject = rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList); va_end(varArgsList); return(returnObject); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withFirstKey:(id)firstKey arguments:(va_list)varArgsList { return(rkl_performDictionaryVarArgsOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, firstKey, varArgsList)); } - (NSArray *)RKL_METHOD_PREPEND(arrayOfDictionariesByMatchingRegex):(NSString *)regex options:(RKLRegexOptions)options range:(NSRange)range error:(NSError **)error withKeys:(id *)keys forCaptures:(int *)captures count:(NSUInteger)count { return(rkl_performRegexOp(self, _cmd, (RKLRegexOp)RKLArrayOfDictionariesOfCapturesOp, regex, options, 0L, self, &range, NULL, error, NULL, count, keys, captures)); } #ifdef _RKL_BLOCKS_ENABLED //////////// #pragma mark - #pragma mark ^Blocks Related NSString Methods #pragma mark -enumerateStringsMatchedByRegex:usingBlock: - (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = NO; rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, 0UL, NULL, &errorFree, NULL, block, NULL); return(errorFree == NO ? NO : YES); } - (BOOL)RKL_METHOD_PREPEND(enumerateStringsMatchedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = NO; rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, enumerationOptions, NULL, &errorFree, error, block, NULL); return(errorFree == NO ? NO : YES); } #pragma mark -enumerateStringsSeparatedByRegex:usingBlock: - (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = NO; rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, 0UL, NULL, &errorFree, NULL, block, NULL); return(errorFree == NO ? NO : YES); } - (BOOL)RKL_METHOD_PREPEND(enumerateStringsSeparatedByRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(void (^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = NO; rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLSplitOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationMatchOp, enumerationOptions, NULL, &errorFree, error, block, NULL); return(errorFree == NO ? NO : YES); } #pragma mark -stringByReplacingOccurrencesOfRegex:usingBlock: - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { return(rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, (RKLRegexOptions)RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, 0UL, NULL, NULL, NULL, NULL, block)); } - (NSString *)RKL_METHOD_PREPEND(stringByReplacingOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { return(rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, enumerationOptions, NULL, NULL, error, NULL, block)); } #endif // _RKL_BLOCKS_ENABLED @end //////////// #pragma mark - @implementation NSMutableString (RegexKitLiteAdditions) #pragma mark -replaceOccurrencesOfRegex: - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement { NSRange searchRange = NSMaxiumRange; NSInteger replacedCount = -1L; rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, (void **)((void *)&replacedCount), 0UL, NULL, NULL); return(replacedCount); } - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement range:(NSRange)searchRange { NSInteger replacedCount = -1L; rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, RKLNoOptions, 0L, self, &searchRange, replacement, NULL, (void **)((void *)&replacedCount), 0UL, NULL, NULL); return(replacedCount); } - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex withString:(NSString *)replacement options:(RKLRegexOptions)options range:(NSRange)searchRange error:(NSError **)error { NSInteger replacedCount = -1L; rkl_performRegexOp(self, _cmd, (RKLRegexOp)(RKLReplaceOp | RKLReplaceMutable), regex, options, 0L, self, &searchRange, replacement, error, (void **)((void *)&replacedCount), 0UL, NULL, NULL); return(replacedCount); } #ifdef _RKL_BLOCKS_ENABLED //////////// #pragma mark - #pragma mark ^Blocks Related NSMutableString Methods #pragma mark -replaceOccurrencesOfRegex:usingBlock: - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = 0UL; NSInteger replacedCount = -1L; NSString *replacedString = rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, RKLNoOptions, self, NSMaxiumRange, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, 0UL, &replacedCount, &errorFree, NULL, NULL, block); if((errorFree == YES) && (replacedCount > 0L)) { [self replaceCharactersInRange:NSMakeRange(0UL, [self length]) withString:replacedString]; } return(replacedCount); } - (NSInteger)RKL_METHOD_PREPEND(replaceOccurrencesOfRegex):(NSString *)regex options:(RKLRegexOptions)options inRange:(NSRange)range error:(NSError **)error enumerationOptions:(RKLRegexEnumerationOptions)enumerationOptions usingBlock:(NSString *(^)(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop))block { NSUInteger errorFree = 0UL; NSInteger replacedCount = -1L; NSString *replacedString = rkl_performEnumerationUsingBlock(self, _cmd, (RKLRegexOp)RKLCapturesArrayOp, regex, options, self, range, (RKLBlockEnumerationOp)RKLBlockEnumerationReplaceOp, enumerationOptions, &replacedCount, &errorFree, error, NULL, block); if((errorFree == YES) && (replacedCount > 0L)) { [self replaceCharactersInRange:range withString:replacedString]; } return(replacedCount); } #endif // _RKL_BLOCKS_ENABLED @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/ImageTLogAdaptor.h
C/C++ Header
// // ImageTLogAdaptor.h // SDWebImage // // Created by LeonChu on 15/8/14. // Copyright (c) 2015年 Taobao lnc. All rights reserved. // #import <Foundation/Foundation.h> @interface ImageTLogAdaptor : NSObject + (BOOL)isDebug; + (BOOL)isInfo; + (BOOL)isError; +(void)printDebugLog:(NSString *) log; +(void)printInfoLog:(NSString *) log; +(void)printErrorLog:(NSString *) log; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/NSData+ImageContentType.h
C/C++ Header
// // Created by Fabrice Aneche on 06/01/14. // Copyright (c) 2014 Dailymotion. All rights reserved. // #import <Foundation/Foundation.h> @interface NSData (ImageContentType) + (NSString *)contentTypeForImageData:(NSData *)data; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDImageCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); /** * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed * asynchronous so it doesn’t add unnecessary latency to the UI. */ @interface SDImageCache : NSObject /** * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** * The maximum length of time to keep an image in the cache, in seconds */ @property (assign, nonatomic) NSInteger maxCacheAge; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxCacheSize; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxOfflineCacheSize; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxHomePageCacheSize; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxWatchCacheSize; /** * Returns global shared cache instance * * @return SDImageCache global instance */ + (SDImageCache *)sharedImageCache; /** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */ - (id)initWithNamespace:(NSString *)ns; /** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */ - (void)addReadOnlyCachePath:(NSString *)path; /** * Store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Store an image into memory and optionally disk cache at the given key. * * @param image The image to store * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage * @param imageData The image data as returned by the server, this representation will be used for disk storage * instead of converting the given image object into a storable/compressed image format in order * to save quality and CPU * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES */ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; /** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image */ - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; /** * Query the disk cache asynchronously. * * @param key The unique key used to store the wanted image * @param needSmallCopy if needSmallCopy is YES, it will return a small copy of an image if no bigger exists, you can use it as a placeholder */ - (NSOperation *)queryDiskCacheForKey:(NSString *)key needSmallCopy:(BOOL)needSmallCopy options:(SDWebImageOptions)options done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock; /** * Query the memory cache synchronously. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; /** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image */ - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; /** * Query the disk cache synchronously after checking the memory cache. * * @param key The unique key used to store the wanted image * @param needSmallCopy if needSmallCopy is YES, it will return a small copy of an image if no bigger exists, you can use it as a placeholder */ - (UIImage *)imageFromDiskCacheForKey:(NSString *)key needSmallCopy:(BOOL)needSmallCopy; /** * Remove the image from memory and disk cache synchronously * * @param key The unique image cache key */ - (void)removeImageForKey:(NSString *)key; /** * Remove the image from memory and optionally disk cache synchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES */ - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; /** * Clear all memory cached images */ - (void)clearMemory; /** * Clear all disk cached images. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */ - (void)clearDiskOnCompletion:(void (^)())completion; /** * Clear all disk cached images * @see clearDiskOnCompletion: */ - (void)clearDisk; /** * Remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock An block that should be executed after cache expiration completes (optional) */ - (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock; /** * Remove all expired cached image from disk * @see cleanDiskWithCompletionBlock: */ - (void)cleanDisk; /** * Get the size used by the disk cache */ - (NSUInteger)getSize; /** * Get the number of images in the disk cache */ - (NSUInteger)getDiskCount; /** * Asynchronously calculate the disk cache's size. */ - (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock; /** * Check if image exists in cache already */ - (BOOL)diskImageExistsWithKey:(NSString *)key; /** * Original disk image data */ - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageCompat.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Jamie Pinkham * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <TargetConditionals.h> #ifdef __OBJC_GC__ #error SDWebImage does not support Objective-C Garbage Collection #endif #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 #error SDWebImage doesn't support Deployement Target version < 5.0 #endif #if !TARGET_OS_IPHONE #import <AppKit/AppKit.h> #ifndef UIImage #define UIImage NSImage #endif #ifndef UIImageView #define UIImageView NSImageView #endif #else #import <UIKit/UIKit.h> #endif #ifndef NS_ENUM #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type #endif #ifndef NS_OPTIONS #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type #endif #if OS_OBJECT_USE_OBJC #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) #define SDDispatchQueueSetterSementics strong #else #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) (dispatch_release(q)) #define SDDispatchQueueSetterSementics assign #endif extern UIImage *SDScaledImageForKey(NSString *key, NSObject *imageOrData); #define dispatch_main_sync_safe(block)\ if ([NSThread isMainThread]) {\ block();\ }\ else {\ dispatch_sync(dispatch_get_main_queue(), block);\ } #define dispatch_main_async_safe(block)\ if ([NSThread isMainThread])\ {\ block();\ }\ else\ {\ dispatch_async(dispatch_get_main_queue(), block);\ } typedef NS_ENUM(NSInteger, ImageCutType) { ImageCutType_None, //不裁剪 ImageCutType_XZ, //缩放裁剪 // ImageCutType_XC //非缩放裁剪 }; typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { /** * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. * This flag disable this blacklisting. */ SDWebImageRetryFailed = 1 << 0, /** * By default, image downloads are started during UI interactions, this flags disable this feature, * leading to delayed download on UIScrollView deceleration for instance. */ SDWebImageLowPriority = 1 << 1, /** * This flag disables on-disk caching */ SDWebImageCacheMemoryOnly = 1 << 2, /** * This flag enables progressive download, the image is displayed progressively during download as a browser would do. * By default, the image is only displayed once completely downloaded. */ SDWebImageProgressiveDownload = 1 << 3, /** * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. * * Use this flag only if you can't make your URLs static with embeded cache busting parameter. */ SDWebImageRefreshCached = 1 << 4, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageContinueInBackground = 1 << 5, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageHandleCookies = 1 << 6, /** * Enable to allow untrusted SSL ceriticates. * Useful for testing purposes. Use with caution in production. */ SDWebImageAllowInvalidSSLCertificates = 1 << 7, /** * By default, image are loaded in the order they were queued. This flag move them to * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which * could take a while). */ SDWebImageHighPriority = 1 << 8, /** * Don't parse the URL */ SDWebImageNoParse = 1 << 9, /** * Curve Animation */ SDWebImageAnimating = 1 << 10, /** * Force no WebP */ SDWebImageNoWebP = 1 << 11, /** * Force no small copy as placeholder */ SDWebImageNoSmallCopy = 1 << 12, /** * When refreshing the same imageView, keep the old image showing */ SDWebImageKeepImageWhenRefreshing = 1 << 13, /** * This flag disables find from disk cache */ SDWebImageNoFindFromDisk = 1 << 14 }; typedef NS_ENUM(NSInteger, SDImageCacheType) { /** * The image wasn't available the SDWebImage caches, but was downloaded from the web. */ SDImageCacheTypeNone, /** * The image was obtained from the disk cache. */ SDImageCacheTypeDisk, /** * The image was obtained from the memory cache. */ SDImageCacheTypeMemory, /** * The image was obtained from the memory cache. but a small copy exists. */ SDImageCacheTypeSmallCopy };
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageDecoder.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * Created by james <https://github.com/mystcolor> on 9/28/11. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" @interface UIImage (ForceDecode) + (UIImage *)decodedImageWithImage:(UIImage *)image; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageDownloader.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { SDWebImageDownloaderLowPriority = 1 << 0, SDWebImageDownloaderProgressiveDownload = 1 << 1, /** * By default, request prevent the of NSURLCache. With this flag, NSURLCache * is used with default policies. */ SDWebImageDownloaderUseNSURLCache = 1 << 2, /** * Call completion block with nil image/imageData if the image was read from NSURLCache * (to be combined with `SDWebImageDownloaderUseNSURLCache`). */ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, /** * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for * extra time in background to let the request finish. If the background task expires the operation will be cancelled. */ SDWebImageDownloaderContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageDownloaderHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL ceriticates. * Useful for testing purposes. Use with caution in production. */ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, /** * Put the image in the high priority queue. */ SDWebImageDownloaderHighPriority = 1 << 7, /** * Execute subband feature. */ // SDWebImageDownloaderSubbandDownload = 1 << 8 }; typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { /** * Default value. All download operations will execute in queue style (first-in-first-out). */ SDWebImageDownloaderFIFOExecutionOrder, /** * All download operations will execute in stack style (last-in-first-out). */ SDWebImageDownloaderLIFOExecutionOrder }; extern NSString *const SDWebImageDownloadStartNotification; extern NSString *const SDWebImageDownloadStopNotification; typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); /** * Asynchronous downloader dedicated and optimized for image loading. */ @interface SDWebImageDownloader : NSObject @property (assign, nonatomic) NSInteger maxConcurrentDownloads; /** * Shows the current amount of downloads that still need to be downloaded */ @property (readonly, nonatomic) NSUInteger currentDownloadCount; /** * The timeout value (in seconds) for the download operation. Default: 15.0. */ @property (assign, nonatomic) NSTimeInterval downloadTimeout; /** * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. */ @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; + (SDWebImageDownloader *)sharedDownloader; /** * Set filter to pick headers for downloading image HTTP request. * * This block will be invoked for each downloading image request, returned * NSDictionary will be used as headers in corresponding HTTP request. */ @property (nonatomic, strong) NSDictionary *(^headersFilter)(NSURL *url, NSDictionary *headers); /** * Set a value for a HTTP header to be appended to each download HTTP request. * * @param value The value for the header field. Use `nil` value to remove the header. * @param field The name of the header field to set. */ - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; /** * Returns the value of the specified HTTP header field. * * @return The value associated with the header field field, or `nil` if there is no corresponding header field. */ - (NSString *)valueForHTTPHeaderField:(NSString *)field; /** * Creates a SDWebImageDownloader async downloader instance with a given URL * * The delegate will be informed when the image is finish downloaded or an error has happen. * * @see SDWebImageDownloaderDelegate * * @param url The URL to the image to download * @param options The options to be used for this download * @param progressBlock A block called repeatedly while the image is downloading * @param completedBlock A block called once the download is completed. * If the download succeeded, the image parameter is set, in case of error, * error parameter is set with the error. The last parameter is always YES * if SDWebImageDownloaderProgressiveDownload isn't use. With the * SDWebImageDownloaderProgressiveDownload option, this block is called * repeatedly with the partial image object and the finished argument set to NO * before to be called a last time with the full image and finished argument * set to YES. In case of error, the finished argument is always YES. * * @return A cancellable SDWebImageOperation */ - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageDownloaderOperation.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> #import "SDWebImageDownloader.h" #import "SDWebImageOperation.h" @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation> @property (strong, nonatomic, readonly) NSMutableURLRequest *request; @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; - (id)initWithRequest:(NSMutableURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock cancelled:(void (^)())cancelBlock; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageManager.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageOperation.h" #import "SDWebImageDownloader.h" #import "SDImageCache.h" #define TBCDNImageModuleDefault @"default" #define TBCDNImageModuleDetail @"detail" #define TBCDNImageModuleShop @"shop" #define TBCDNImageModuleSearch @"search" #define TBCDNImageModuleWaterFlow @"waterflow" #define TBCDNImageModuleWeitao @"weitao" #define TBCDNImageModuleWeapp @"weapp" #define TBCDNImageModuleBala @"bala" #define TBCDNImageModuleHomePage @"homepage" #define TBCDNImageModuleWebView @"webview" typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType); typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished); typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); @class SDWebImageManager; @protocol SDWebImageManagerDelegate <NSObject> @optional /** * Controls which image should be downloaded when the image is not found in the cache. * * @param imageManager The current `SDWebImageManager` * @param imageURL The url of the image to be downloaded * * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. */ - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; /** * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. * NOTE: This method is called from a global queue in order to not to block the main thread. * * @param imageManager The current `SDWebImageManager` * @param image The image to transform * @param imageURL The url of the image to transform * * @return The transformed image object. */ - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; @end /** * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). * You can use this class directly to benefit from web image downloading with caching in another context than * a UIView. * * Here is a simple example of how to use SDWebImageManager: * * @code SDWebImageManager *manager = [SDWebImageManager sharedManager]; [manager downloadWithURL:imageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { if (image) { // do something with image } }]; * @endcode */ @interface SDWebImageManager : NSObject @property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly) SDImageCache *imageCache; @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; /** * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can * be used to remove dynamic part of an image URL. * * The following example sets a filter in the application delegate that will remove any query-string from the * URL before to use it as a cache key: * * @code [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; return [url absoluteString]; }]; * @endcode */ @property (strong) NSString *(^cacheKeyFilter)(NSURL *url); /** * Returns global SDWebImageManager instance. * * @return SDWebImageManager shared instance */ + (SDWebImageManager *)sharedManager; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark 基本 /** * 基本静默下载图片接口 * 注意:这个接口谨慎使用,因为是原图下载,如果过大会耗费流量 * * @param url 图片url */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 添加图片大小 * 注意:这个接口只有在你确定图片大小,不需要底层再适配大小时使用,如果需要适配,请用楼下接口 * * @param url 图片url * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url imageSize:(CGSize)imageSize completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加裁切类型 * * @param url 图片url * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加裁切类型 * * @param url 图片url * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 * @param options 选项参数 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加裁切类型 * * @param url 图片url * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 * @param options 选项参数 * @param progress 进度回调 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark 组件定位 /** * 基本静默下载图片接口 * 注意:这个接口谨慎使用,因为是原图下载,如果过大会耗费流量 * * @param url 图片url */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url module:(NSString *)module completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 添加图片大小 * 注意:这个接口只有在你确定图片大小,不需要底层再适配大小时使用,如果需要适配,请用楼下接口 * * @param url 图片url * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url module:(NSString *)module imageSize:(CGSize)imageSize completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加裁切类型 * * @param url 图片url * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url module:(NSString *)module imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加选项参数 * * @param url 图片url * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 * @param options 选项参数 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url module:(NSString *)module imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 对应添加进度回调 * * @param url 图片url * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param imageSize 图像大小(注意: 如果要指定大小,需要自己处理 Retina Scale,不然可以直接用 CGSizeZero 忽略) * @param cutType 指定裁剪类型 * @param options 选项参数 * @param progress 进度回调 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url module:(NSString *)module imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 老接口兼容 * * @param url 图片url * @param options 选项参数 * @param progress 进度回调 */ - (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock; /** * 新接口适配:官方版本3.7.0以上开始使用此方法 * * @param url 图片url * @param options 选项参数 * @param progress 进度回调 */ - (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; /** * Cancel all current opreations */ - (void)cancelAll; /** * Check one or more operations running */ - (BOOL)isRunning; /** * Check if image has already been cached */ - (BOOL)diskImageExistsForURL:(NSURL *)url; /** * Get cache key for url */ - (NSString *)cacheKeyForURL:(NSURL *)url; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/SDWebImageOperation.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <Foundation/Foundation.h> @protocol SDWebImageOperation <NSObject> - (void)cancel; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/TBImagePerformanceDate.h
C/C++ Header
// // TBImagePerformanceDate.h // SDWebImage // // Created by zhangtianshun on 15/4/8. // Copyright (c) 2015年 Taobao lnc. All rights reserved. // #import <Foundation/Foundation.h> @interface TBImagePerformanceDate : NSObject @property (nonatomic, strong) NSMutableDictionary* userInfo; @property (nonatomic, strong) NSDate *beginDate; @property (nonatomic, strong) NSDate *endDate; @property (nonatomic, strong) NSString *url; @property (nonatomic, strong) NSString *eventType; @property (nonatomic, strong) NSString *bizName; @property (nonatomic, strong) NSError *error; @property (nonatomic, strong) NSString *dataFrom; // 图片来源:0.网络,1.memcache,2.磁盘精确匹配,3缓存裁剪 @property (nonatomic, assign) NSUInteger eventId; @property (nonatomic, strong) NSDate *prePhaseDate; @property (nonatomic, strong) NSString *prePhaseName; @property (nonatomic, strong) NSMutableArray *normalPhaseArray; - (void)initWithParam:(NSString *)url module:(NSString *)module; //- (void)endPerformanceUserTrack; - (id)objectByKey:(NSString *)key; - (NSString *)getDataFromCode; - (NSString *)getErrorCode; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/TBImageUserTrack.h
C/C++ Header
// // TBImageUserTrack.h // TBCDNImage // // Created by 贾复 on 14/8/4. // Copyright (c) 2014年 Taobao lnc. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface TBImageUserTrack : NSObject + (TBImageUserTrack*)shareTrack; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - 缓存性能 //- (void)increaseMemoryHit; //- (void)increaseDiskHit; //- (void)increaseRemoteHit; //- (void)appendWriteTotalBytes:(NSUInteger)bytes; //- (void)appendWriteTimeCost:(NSTimeInterval)cost; //- (void)appendReadTotalBytes:(NSUInteger)bytes; //- (void)appendReadTimeCost:(NSTimeInterval)cost; - (void)startTrackIfNeeded; - (void)restore; - (void)store; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - 全链路性能 /* * 图片链路埋点 的起始点 * * @param url 所在页面 * @param modlue 调用图片库的模块名称 * @param userInfo 上传的数据字典 */ - (void)beginImageTrace:(NSString *)url module:(NSString *)module userInfo:(NSDictionary *)userInfo; /* 针对业务过程中的某个中间时间点进行一条打点,调用后,在end的时候,会在args里增加一条@“phase-start”,或者 @“phase-phase0”的耗时的记录 Begin________A_______B_______C_______End, 调用 addPerformancePhase:A, addPerformancePhase:B, addPerformancePhase:C, 在UT记录里就会记录A-begin:耗时,B-A:耗时,C-B:耗时,这样的信息 主要用于解决串行时各时间点的时间差 */ - (void)addPhase:(NSString *)phase url:(NSString *)url userInfo:(NSDictionary *)userInfo; /*! * 全链路埋点:Image数据来源监控 * * @param dataFrom 数据来源:网络(Network),内存缓存(MemCache),磁盘精确匹配(DiskCache),缓存裁剪(DiskCacheCut) * @param page 所在页面 * @param eventType 事件类型,eg:load、click * @param eventId 埋点事件id */ - (void)addDataFrom:(NSString *)dataFrom url:(NSString *)url; /** * 全链路埋点 的结束点,自动调用clear, 这里的page和eventType 需要和start调用中匹配。加参数,解决不同业务交叉调用start的情况,但对于同个业务连续调多次start还是无法处理,若要解决需要开放内部token * @param page 所在页面 * @param eventType 事件类型,eg:load、click * @param eventId 埋点事件id * @param userInfo 放入args中的数据 */ - (void)endImageTrace:(NSString *)url userInfo:(NSDictionary *)userInfo; - (void)commitErrorMonitor:(NSString *)url error:(NSError *)error; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/TBImageUtility.h
C/C++ Header
// // TBImageUtility.h // SDWebImage // // Created by 贾复 on 14/11/19. // Copyright (c) 2014年 Taobao lnc. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface TBImageUtility : NSObject + (CGSize)imageSizeFromURLString:(NSString *)urlString; + (NSString *)imageBaseUrlStringFromURLString:(NSString *)urlString; // 检查并补齐URL Schema + (NSURL*)checkURLSchema:(NSURL *)inputUrl; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIButton+WebCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageManager.h" @interface UIButton (WebCache) //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - 按钮图 #pragma mark 基本 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param options 选项 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark 结束回调 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; /** * SD 老接口兼容 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark 组件定位 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - 背景图 #pragma mark 基本 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param options 选项 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark 结束回调 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; /** * SD 老接口兼容 * * @param url 图片请求链接 * @param state button状态 * @param placeholder 占位图 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark 组件定位 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param state button状态 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; /** * Cancel the current download */ - (void)cancelCurrentImageLoad; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIImage+GIF.h
C/C++ Header
// // UIImage+GIF.h // LBGIFImage // // Created by Laurin Brandner on 06.01.12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (GIF) + (UIImage *)sd_animatedGIFNamed:(NSString *)name; + (UIImage *)sd_animatedGIFWithData:(NSData *)data; - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIImage+MultiFormat.h
C/C++ Header
// // UIImage+MultiFormat.h // SDWebImage // // Created by Olivier Poitrey on 07/06/13. // Copyright (c) 2013 Dailymotion. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (MultiFormat) + (UIImage *)sd_imageWithData:(NSData *)data; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIImage+Scale.h
C/C++ Header
// // UIImage+Scale.h // TBUtility // // Created by Dafeng Jin on 14/7/22. // // #import <UIKit/UIKit.h> @interface UIImage (Scale) - (UIImage *)imageByScalingAndCroppingToSize:(CGSize)size; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIImage+WebP.h
C/C++ Header
// // UIImage+WebP.h // SDWebImage // // Created by Olivier Poitrey on 07/06/13. // Copyright (c) 2013 Dailymotion. All rights reserved. // #import <UIKit/UIKit.h> // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device void WebPInitPremultiplyNEON(void); void WebPInitUpsamplersNEON(void); void VP8DspInitNEON(void); @interface UIImage (WebP) + (UIImage *)sd_imageWithWebPData:(NSData *)data; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/SDWebImage/SDWebImage.framework/Versions/A/Headers/UIImageView+WebCache.h
C/C++ Header
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDWebImageManager.h" @interface UIImageView (WebCache) //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark 基本 /** * 基本图片请求调用 * * @param url 图片请求链接 */ - (void)setImageWithURL:(NSURL *)url; /** * 添加占位图 * * @param url 图片请求链接 * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; /** * 添加占位图 * * @param url 图片请求链接 * @param placeholder 占位图 * @param options 选项 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己 处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize; /** * 添加图片大小 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType; /** * 添加options参数选项 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options; /** * 添加progress回调 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark 结束回调 /** * 基本图片请求调用 * * @param url 图片请求链接 */ - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; /** * SD老接口兼容 * * @param url 图片请求链接 * @param placeholder 占位图 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark 组件定位 /** * 基本图片请求调用 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加占位图 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加裁剪信息参数 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加图片大小 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加options参数选项 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock; /** * 添加progress回调 * * @param url 图片请求链接 * @param module 调用组件模块名,为了对不同模块进行不同配置,默认则写TBCDNImageModuleDefault * @param placeholder 占位图 * @param imageSize 指定图片大小(注意:一般情况下不需要指定或可以直接设置为 CGSizeZero。当你调用接口时 imageView 的 frame 还未初始化,用这个指定。指定时必须自己处理 Retina Scale) * @param cutType 指定裁剪类型 * @param options 参数选项 * @param progressBlock 进度回调 */ - (void)setImageWithURL:(NSURL *)url module:(NSString *)module placeholderImage:(UIImage *)placeholder imageSize:(CGSize)imageSize cutType:(ImageCutType)cutType options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock; /** * Cancel the current download */ - (void)cancelCurrentImageLoad; - (void)cancelCurrentArrayLoad; // 以下为适配官方3.7.x的新接口 - (void)sd_setImageWithURL:(NSURL *)url; - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-AFNetworking/Pods-AFNetworking-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_AFNetworking : NSObject @end @implementation PodsDummy_Pods_AFNetworking @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-DXPhotoBrowser/Pods-DXPhotoBrowser-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_DXPhotoBrowser : NSObject @end @implementation PodsDummy_Pods_DXPhotoBrowser @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-DXRefresh/Pods-DXRefresh-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_DXRefresh : NSObject @end @implementation PodsDummy_Pods_DXRefresh @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-Nimbus/Pods-Nimbus-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_Nimbus : NSObject @end @implementation PodsDummy_Pods_Nimbus @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-Placeholder/Pods-Placeholder-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_Placeholder : NSObject @end @implementation PodsDummy_Pods_Placeholder @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-RegexKitLite/Pods-RegexKitLite-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_RegexKitLite : NSObject @end @implementation PodsDummy_Pods_RegexKitLite @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-SDWebImage/Pods-SDWebImage-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_SDWebImage : NSObject @end @implementation PodsDummy_Pods_SDWebImage @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods-WebP/Pods-WebP-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_WebP : NSObject @end @implementation PodsDummy_Pods_WebP @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-dummy.m
Objective-C
#import <Foundation/Foundation.h> @interface PodsDummy_Pods : NSObject @end @implementation PodsDummy_Pods @end
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-environment.h
C/C++ Header
// To check if a library is compiled with CocoaPods you // can use the `COCOAPODS` macro definition which is // defined in the xcconfigs so it is available in // headers also when they are imported in the client // project. // AFNetworking #define COCOAPODS_POD_AVAILABLE_AFNetworking #define COCOAPODS_VERSION_MAJOR_AFNetworking 2 #define COCOAPODS_VERSION_MINOR_AFNetworking 6 #define COCOAPODS_VERSION_PATCH_AFNetworking 0 // AFNetworking/NSURLConnection #define COCOAPODS_POD_AVAILABLE_AFNetworking_NSURLConnection #define COCOAPODS_VERSION_MAJOR_AFNetworking_NSURLConnection 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_NSURLConnection 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_NSURLConnection 0 // AFNetworking/NSURLSession #define COCOAPODS_POD_AVAILABLE_AFNetworking_NSURLSession #define COCOAPODS_VERSION_MAJOR_AFNetworking_NSURLSession 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_NSURLSession 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_NSURLSession 0 // AFNetworking/Reachability #define COCOAPODS_POD_AVAILABLE_AFNetworking_Reachability #define COCOAPODS_VERSION_MAJOR_AFNetworking_Reachability 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_Reachability 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_Reachability 0 // AFNetworking/Security #define COCOAPODS_POD_AVAILABLE_AFNetworking_Security #define COCOAPODS_VERSION_MAJOR_AFNetworking_Security 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_Security 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_Security 0 // AFNetworking/Serialization #define COCOAPODS_POD_AVAILABLE_AFNetworking_Serialization #define COCOAPODS_VERSION_MAJOR_AFNetworking_Serialization 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_Serialization 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_Serialization 0 // AFNetworking/UIKit #define COCOAPODS_POD_AVAILABLE_AFNetworking_UIKit #define COCOAPODS_VERSION_MAJOR_AFNetworking_UIKit 2 #define COCOAPODS_VERSION_MINOR_AFNetworking_UIKit 6 #define COCOAPODS_VERSION_PATCH_AFNetworking_UIKit 0 // DXPhotoBrowser #define COCOAPODS_POD_AVAILABLE_DXPhotoBrowser #define COCOAPODS_VERSION_MAJOR_DXPhotoBrowser 0 #define COCOAPODS_VERSION_MINOR_DXPhotoBrowser 1 #define COCOAPODS_VERSION_PATCH_DXPhotoBrowser 2 // DXPhotoBrowser/ImageUtils #define COCOAPODS_POD_AVAILABLE_DXPhotoBrowser_ImageUtils #define COCOAPODS_VERSION_MAJOR_DXPhotoBrowser_ImageUtils 0 #define COCOAPODS_VERSION_MINOR_DXPhotoBrowser_ImageUtils 1 #define COCOAPODS_VERSION_PATCH_DXPhotoBrowser_ImageUtils 2 // DXPhotoBrowser/InternalViews #define COCOAPODS_POD_AVAILABLE_DXPhotoBrowser_InternalViews #define COCOAPODS_VERSION_MAJOR_DXPhotoBrowser_InternalViews 0 #define COCOAPODS_VERSION_MINOR_DXPhotoBrowser_InternalViews 1 #define COCOAPODS_VERSION_PATCH_DXPhotoBrowser_InternalViews 2 // DXRefresh #define COCOAPODS_POD_AVAILABLE_DXRefresh #define COCOAPODS_VERSION_MAJOR_DXRefresh 0 #define COCOAPODS_VERSION_MINOR_DXRefresh 1 #define COCOAPODS_VERSION_PATCH_DXRefresh 0 // Nimbus #define COCOAPODS_POD_AVAILABLE_Nimbus #define COCOAPODS_VERSION_MAJOR_Nimbus 1 #define COCOAPODS_VERSION_MINOR_Nimbus 2 #define COCOAPODS_VERSION_PATCH_Nimbus 0 // Nimbus/AttributedLabel #define COCOAPODS_POD_AVAILABLE_Nimbus_AttributedLabel #define COCOAPODS_VERSION_MAJOR_Nimbus_AttributedLabel 1 #define COCOAPODS_VERSION_MINOR_Nimbus_AttributedLabel 2 #define COCOAPODS_VERSION_PATCH_Nimbus_AttributedLabel 0 // Nimbus/Badge #define COCOAPODS_POD_AVAILABLE_Nimbus_Badge #define COCOAPODS_VERSION_MAJOR_Nimbus_Badge 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Badge 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Badge 0 // Nimbus/CSS #define COCOAPODS_POD_AVAILABLE_Nimbus_CSS #define COCOAPODS_VERSION_MAJOR_Nimbus_CSS 1 #define COCOAPODS_VERSION_MINOR_Nimbus_CSS 2 #define COCOAPODS_VERSION_PATCH_Nimbus_CSS 0 // Nimbus/Collections #define COCOAPODS_POD_AVAILABLE_Nimbus_Collections #define COCOAPODS_VERSION_MAJOR_Nimbus_Collections 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Collections 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Collections 0 // Nimbus/Core #define COCOAPODS_POD_AVAILABLE_Nimbus_Core #define COCOAPODS_VERSION_MAJOR_Nimbus_Core 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Core 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Core 0 // Nimbus/Interapp #define COCOAPODS_POD_AVAILABLE_Nimbus_Interapp #define COCOAPODS_VERSION_MAJOR_Nimbus_Interapp 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Interapp 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Interapp 0 // Nimbus/Launcher #define COCOAPODS_POD_AVAILABLE_Nimbus_Launcher #define COCOAPODS_VERSION_MAJOR_Nimbus_Launcher 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Launcher 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Launcher 0 // Nimbus/Models #define COCOAPODS_POD_AVAILABLE_Nimbus_Models #define COCOAPODS_VERSION_MAJOR_Nimbus_Models 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Models 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Models 0 // Nimbus/NetworkControllers #define COCOAPODS_POD_AVAILABLE_Nimbus_NetworkControllers #define COCOAPODS_VERSION_MAJOR_Nimbus_NetworkControllers 1 #define COCOAPODS_VERSION_MINOR_Nimbus_NetworkControllers 2 #define COCOAPODS_VERSION_PATCH_Nimbus_NetworkControllers 0 // Nimbus/NetworkImage #define COCOAPODS_POD_AVAILABLE_Nimbus_NetworkImage #define COCOAPODS_VERSION_MAJOR_Nimbus_NetworkImage 1 #define COCOAPODS_VERSION_MINOR_Nimbus_NetworkImage 2 #define COCOAPODS_VERSION_PATCH_Nimbus_NetworkImage 0 // Nimbus/Overview #define COCOAPODS_POD_AVAILABLE_Nimbus_Overview #define COCOAPODS_VERSION_MAJOR_Nimbus_Overview 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Overview 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Overview 0 // Nimbus/PagingScrollView #define COCOAPODS_POD_AVAILABLE_Nimbus_PagingScrollView #define COCOAPODS_VERSION_MAJOR_Nimbus_PagingScrollView 1 #define COCOAPODS_VERSION_MINOR_Nimbus_PagingScrollView 2 #define COCOAPODS_VERSION_PATCH_Nimbus_PagingScrollView 0 // Nimbus/Photos #define COCOAPODS_POD_AVAILABLE_Nimbus_Photos #define COCOAPODS_VERSION_MAJOR_Nimbus_Photos 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Photos 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Photos 0 // Nimbus/Textfield #define COCOAPODS_POD_AVAILABLE_Nimbus_Textfield #define COCOAPODS_VERSION_MAJOR_Nimbus_Textfield 1 #define COCOAPODS_VERSION_MINOR_Nimbus_Textfield 2 #define COCOAPODS_VERSION_PATCH_Nimbus_Textfield 0 // Nimbus/WebController #define COCOAPODS_POD_AVAILABLE_Nimbus_WebController #define COCOAPODS_VERSION_MAJOR_Nimbus_WebController 1 #define COCOAPODS_VERSION_MINOR_Nimbus_WebController 2 #define COCOAPODS_VERSION_PATCH_Nimbus_WebController 0 // Placeholder #define COCOAPODS_POD_AVAILABLE_Placeholder #define COCOAPODS_VERSION_MAJOR_Placeholder 0 #define COCOAPODS_VERSION_MINOR_Placeholder 1 #define COCOAPODS_VERSION_PATCH_Placeholder 1 // RegexKitLite #define COCOAPODS_POD_AVAILABLE_RegexKitLite #define COCOAPODS_VERSION_MAJOR_RegexKitLite 4 #define COCOAPODS_VERSION_MINOR_RegexKitLite 0 #define COCOAPODS_VERSION_PATCH_RegexKitLite 0 // SDWebImage #define COCOAPODS_POD_AVAILABLE_SDWebImage // This library does not follow semantic-versioning, // so we were not able to define version macros. // Please contact the author. // Version: 3.7.0.39. // WebP #define COCOAPODS_POD_AVAILABLE_WebP #define COCOAPODS_VERSION_MAJOR_WebP 2 #define COCOAPODS_VERSION_MINOR_WebP 0 #define COCOAPODS_VERSION_PATCH_WebP 0
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/Target Support Files/Pods/Pods-resources.sh
Shell
#!/bin/sh set -e mkdir -p "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" install_resource() { case $1 in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" ;; *.framework) echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm\"" xcrun mapc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcmappingmodel`.cdm" ;; *.xcassets) ;; /*) echo "$1" echo "$1" >> "$RESOURCES_TO_COPY" ;; *) echo "${PODS_ROOT}/$1" echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" ;; esac } install_resource "Nimbus/src/overview/resources/NimbusOverviewer.bundle" install_resource "Nimbus/src/photos/resources/NimbusPhotos.bundle" install_resource "Nimbus/src/webcontroller/resources/NimbusWebController.bundle" install_resource "${BUILT_PRODUCTS_DIR}/DXPhotoBrowser.bundle" install_resource "${BUILT_PRODUCTS_DIR}/DXRefresh.bundle" install_resource "${BUILT_PRODUCTS_DIR}/Placeholder.bundle" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]]; then rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ `find . -name '*.xcassets' | wc -l` -ne 0 ] then case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac find "${PWD}" -name "*.xcassets" -print0 | xargs -0 actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay
Example/Pods/WebP/WebP.framework/Headers/config.h
C/C++ Header
/* src/webp/config.h. Generated from config.h.in by configure. */ /* src/webp/config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ /* #undef AC_APPLE_UNIVERSAL_BUILD */ /* Set to 1 if __builtin_bswap16 is available */ #define HAVE_BUILTIN_BSWAP16 1 /* Set to 1 if __builtin_bswap32 is available */ #define HAVE_BUILTIN_BSWAP32 1 /* Set to 1 if __builtin_bswap64 is available */ #define HAVE_BUILTIN_BSWAP64 1 /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <GLUT/glut.h> header file. */ /* #undef HAVE_GLUT_GLUT_H */ /* Define to 1 if you have the <GL/glut.h> header file. */ /* #undef HAVE_GL_GLUT_H */ /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <OpenGL/glut.h> header file. */ /* #undef HAVE_OPENGL_GLUT_H */ /* Have PTHREAD_PRIO_INHERIT. */ #define HAVE_PTHREAD_PRIO_INHERIT 1 /* Define to 1 if you have the <shlwapi.h> header file. */ /* #undef HAVE_SHLWAPI_H */ /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the <wincodec.h> header file. */ /* #undef HAVE_WINCODEC_H */ /* Define to 1 if you have the <windows.h> header file. */ /* #undef HAVE_WINDOWS_H */ /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define to 1 if your C compiler doesn't accept -c and -o together. */ /* #undef NO_MINUS_C_MINUS_O */ /* Name of package */ #define PACKAGE "libwebp" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "http://code.google.com/p/webp/issues" /* Define to the full name of this package. */ #define PACKAGE_NAME "libwebp" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "libwebp 0.4.2" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "libwebp" /* Define to the home page for this package. */ #define PACKAGE_URL "http://developers.google.com/speed/webp" /* Define to the version of this package. */ #define PACKAGE_VERSION "0.4.2" /* Define to necessary symbol if this constant uses a non-standard name on your system. */ /* #undef PTHREAD_CREATE_JOINABLE */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ #define VERSION "0.4.2" /* Enable experimental code */ /* #undef WEBP_EXPERIMENTAL_FEATURES */ /* Define to 1 to force aligned memory operations */ /* #undef WEBP_FORCE_ALIGNED */ /* Set to 1 if AVX2 is supported */ /* #undef WEBP_HAVE_AVX2 */ /* Set to 1 if GIF library is installed */ /* #undef WEBP_HAVE_GIF */ /* Set to 1 if OpenGL is supported */ /* #undef WEBP_HAVE_GL */ /* Set to 1 if JPEG library is installed */ /* #undef WEBP_HAVE_JPEG */ /* Set to 1 if PNG library is installed */ /* #undef WEBP_HAVE_PNG */ /* Set to 1 if SSE2 is supported */ /* #undef WEBP_HAVE_SSE2 */ /* Set to 1 if TIFF library is installed */ /* #undef WEBP_HAVE_TIFF */ /* Undefine this to disable thread support. */ #define WEBP_USE_THREAD 1 /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN /* # undef WORDS_BIGENDIAN */ # endif #endif
xiekw2010/DXPhotoBrowser
2
A photo browser for displaying a bunch of images one by one
Objective-C
xiekw2010
David Tse
Alipay